2015-07-18 18 views
8

Mam usługa tak:angularjs usługa nie jest funkcją

app.service('Utilities', function() { 
    this.sum = function(items, prop) { 
    var count, total; 
    total = 0; 
    count = 0; 
    if (items === null) { 
     total = 0; 
    } 
    while (count < items.length) { 
     total += items[count][prop] * 1 || 0; 
     count++; 
    } 
    return total; 
    }; 
}); 

i kontroler tak:

app.controller('writeCtrl', function($scope, Utilities, students) { 
    $scope.students = students; 
    $scope.total_age = Utilities.sum($scope.students, 'age'); 
}); 

I zachować uzyskiwanie błąd

Typerror: Utilities.sum is not a function

Która jest mylące, ponieważ około tuzin innych funkcji w ramach usługi Utilities działa dobrze. Co powoduje problem i jak uruchomić funkcję?

Edit Aktualna wersja coffeescript

app.service 'Utilities', -> 
    @sum = (items, prop) -> 
    total = 0 
    count = 0 
    if items == null 
     total = 0 
    while count < items.length 
     total += (items[count][prop]*1 || 0) 
     count++ 
    return total 

app.controller 'writeCtrl', ($scope, Utilities, students) -> 
    $scope.students = students 
    $scope.total_age = Utilities.sum($scope.students, 'age') 

Rozwiązanie:

funkcje coffeescript potrzebujemy powrotu:

App.service 'Utilities', -> 
    ..... 
    return 
+1

Czy to jest prawidłowe wcięcie twojego kodu? CoffeeScript jest znaczący i wydaje się, że masz błąd wcięcia na linii 3 –

+0

@DanPantry Hi Dan, wcięcie musiało zostać popsute, kiedy wkleiłem to na stackoverflow, ale tak, wcięcie w moim rzeczywistym kodzie jest poprawne. –

Odpowiedz

7

obsługa nigdy zwraca obiekt, w zasadzie wiąże metodę lub zmienne w stosunku do kontekstu; nic tylko próba this & następnie zwraca nowy object, który zawiera wszystkie rzeczy, które były związane z this.

Kod

app.service('Utilities', function() { 
    this.sum = function(items, prop) { 
    var count, total; 
    total = 0; 
    count = 0; 
    if (items === null) { 
     total = 0; 
    } 
    while (count < items.length) { 
     total += items[count][prop] * 1 || 0; 
     count++; 
    } 
    return total; 
    }; 

    // 
    // ..other utility method should lies here.. 
    //..do your stuff 
}); 

Aktualizacja

powinien zmienić swoją usługę coffeescript z

app.service 'Utilities' -> 

do

app.service 'Utilities'() -> 
+0

Przepraszam, to literówka z aplikacji js2coffee. Używam @ sum = (items, prop) -> with coffeescript. –

+0

@ Ryan.lay wklej swój aktualny kod zamiast wersji transpiled. –

+0

@ Ryan.lay możesz zaktualizować kod, a następnie ... co masz w swoim kodzie –