2014-02-07 59 views
1

我有一個AngularJS和非常基本的數學問題。當我從我的Firebase中選擇數據時,我想添加它們。AngularJS說1 + 1是11

這裏是我的代碼:

$scope.project.$on('loaded', function(value) { 
    console.log(value); // data loaded from Firebase 
    console.log(value.name); // subset of the returned value 

    angular.isNumber(value.firstmatch); 
    angular.isNumber(value.secondmatch); 



    $scope.project.points = ((value.firstmatch) + (value.firstmatch)); 

而這種輸出11是的,在firstmatch值爲1

謝謝!

+4

添加在這種情況下被解釋爲字符串連接,而不是數相加:「1」 +「1」 =「11」 。 – duffymo

+0

[This can help](http://stackoverflow.com/questions/17351831/why-is-angular-isnumber-not-working-as-expected),看看評論 – lavrik

回答

6

所以你的數據是給你的字符串,只需將它們轉換爲數字:

$scope.project.$on('loaded', function(value) { 
    console.log(value); // data loaded from Firebase 
    console.log(value.name); // subset of the returned value 

    //angular.isNumber(value.firstmatch); 
    //angular.isNumber(value.secondmatch); 



    $scope.project.points = parseInt(value.firstmatch, 10) + parseInt(value.firstmatch,10);