2016-03-05 60 views
1

我在左边有按钮的字段列表(todos)。我想单击其中一个按钮,以便计算此特定字段的值。AngularJS - 计算每个字段的值

什么我得到的是点击特定按钮计算并显示所有字段相同的结果

这是我写的:

<h1 ng-show="myVar"> 
    <ul> 
    <li ng-repeat="todo in todos"> 
     <button ng-show="!editing[$index]" ng-click="edit($index)">click</button> 
     <h2> Result is:{{result}}</h2> 
     {{todo.name}} 
    </li> 
    </ul> 
    </h1> 

和控制器

 $scope.edit = function(index){ 

     var todo = $scope.todos[index]; 
     var counter = 0; 
     angular.forEach($scope.todos,function(value,index){ 
      if (todo.topic == 'important') 
      {counter = counter+1;} 

     }) 
     $scope.result = counter; 
     } 

我在做什么错?

回答

2

基本上已用于结合的scoperesult变量不是已内部控制器范围所定义的相同范围的变量。

因为ng-repeat不会工作在一个完全不同的方式,当它通过提供收集循环渲染DOM(这里的todos),它创造了它prototypically从它的父作用域继承每个迭代一个新的范围。

不要使用Dot Rule而定义模型,以便它遵循原型继承,

$scope.model = {}; 

//then use 
$scope.model.result = result; 

HTML

<h2> Result is:{{model.result}}</h2> 

其他方式来解决这问题出将使用而controllerAs方法定义控制器,但在这种情况下,您需要读取$scope &应替换为this t的控制器功能。

+0

这非常有帮助!现在它计算出正确的结果。 唯一的是我看到所有字段旁边的结果。我怎样才能改变它,结果只会显示在特定的领域,而不是每个人? –

+0

@ A.Sh然后传递该特定对象来编辑像ng-click =“edit(todo)”这样的方法,并将结果属性添加到todo对象中,这样就可以通过使用'todo.result '。 –

+0

todo是来自db的字段...你是否要将结果属性添加到数据库?因为我不想更改分贝。我可以做不同吗? –

0

您使用相同的index变量名作为函数输入参数 - function(index)和forEach循环,function(value,index){ - 它会被覆盖。

//here 
$scope.edit = function(index){ 

    var todo = $scope.todos[index]; 
    var counter = 0; 
//and here 
    angular.forEach($scope.todos,function(value,index){ 
+0

但我为每个按钮调用这个函数,所以'$ scope.edit = function(index){'中的索引每次都会改变,不是? –