2015-04-17 142 views
2
<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  </script> 
</head> 
<body> 
    <div ng-app="myApp" ng-controller="personCtrl">{{count()}}</div> 
    <script> 

    var app = angular.module('myApp', []); 

    app.controller('personCtrl', function($scope) { 
     $scope.listarray=[1,2,3,4]; 
     var count=0  

     $scope.count = function() { 
      angular.forEach($scope.listarray,function(value,key){ 
       count=count+1; 
      }); 
      return count; 
     } 
    }); 
    </script> 
</body> 
</html> 

上述代码显示的答案是88。当var count在里面时count功能显示4但在count功能外显示88。为什么会发生?伯爵的答案是88:为什么?

+0

o真的是显示88?你能告诉我结果在小提琴手吗? –

+2

http://jsfiddle.net/satpalsingh/0s12zf1k/,只需在函数内定义'var count'即可。 _OR_ YOu可以简单地使用'listarray.length'像http://jsfiddle.net/satpalsingh/Lc4yvbc9/ – Satpal

回答

3

行为的原因是您已将count()函数附加到$scope并在绑定表达式中使用它。在AngularJS中,$digest周期来计算表达式并渲染视图可以运行多次。

在伪代码$digest周期看起来是这样的:

  1. 对于每个$scope财产
  2. 检查$scope属性更改(通过评估例如绑定表达式)
  3. 如果改变,呼叫改变处理程序(可以更新更多的示波器变量),否则继续
  4. 重复所有示波器
  5. 重复循环1-4直到$scope性能stabalise
+0

非常感谢你 –

0

你为什么要使用功能或每个循环中,您可以只使用长度财产$ scope.listarray.length; 试试这个:

<head> 
<script src=  "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  </script> 
    </head> 

    <body> 

<div ng-app="myApp" ng-controller="personCtrl"> 
{{count}} 

    </div> 

<script> 

    var app = angular.module('myApp', []); 

    app.controller('personCtrl', function($scope) { 
    $scope.listarray=[1,2,3,4]; 

    $scope.count = $scope.listarray.length;  
    }); 
    </script> 

    </body> 
    </html> 
0

您已经创建了无限循环。每当值发生更改时都会调用函数count()。例如,你可以检查数值是否已经改变

$scope.count = function() { 
     if(count !== 0){return count;} 
     angular.forEach($scope.listarray,function(value,key){ 
      console.log('value', value); 
      count=count+1; 
     }); 
     return count; 
    } 
+0

非常感谢你 –