angularjs - the diffrence between angular.foreach and "for" -


i tried todo example in angular home page (no.2) , modified little code cause wired problem. when add 2 todo, dispaly ok displayed “4 of 4 remain [archive]”,then select 2 todo item , click "acrhive". result should “2 of 2 remain [archive]", acctually display “2 of 4 remain [archive]". replace ”for“ loop wiht "angular.foreach" function, result correct. can explain diffrence when use between "for loop" , "angular.foreach"? coding shown belowing:

<html> <head> <meta charset="utf8"> <script src="js/angular.js"></script>  </head> <body ng-app ng-controller="todo"> <span>{{remains()}} of {{total}} remain</span><span>[<a href="javascript:void(0)" ng-click="archive()">archive</a>]</span> <ul>     <li ng-repeat="todo in todos">         <input type="checkbox" ng-model="todo.checked">{{todo.item}}         </input>     </li>     <form ng-submit="addtodo()">     <input type="text" ng-model="todoitem" placeholder="add todo list here"></input>     <span><input class="btn-primary" type="submit" value="add"></input></span>     </form> </ul> <script> var todo = function ($scope) {     $scope.todos = [         {item:"discuss team",checked:false},         {item:"mail jack",checked:false}     ];      $scope.total = $scope.todos.length;     $scope.remains = function() {         var count =0;         (var i=0;i<$scope.todos.length;i++) {             count += $scope.todos[i].checked?0:1         };         return count;     };     $scope.action= function($index) {         $scope.todos[$index].checked=!todos[$index].checked         $scope.remain += todos[$index].checked?-1:1;     };     $scope.addtodo = function() {         $scope.total ++;         $scope.todos.push({item:$scope.todoitem,checked:false});         $scope.todoitem = '';     };      $scope.archive = function() {         var oldtodos = $scope.todos;         $scope.todos = [];          (var i=0;oldtodos.length-1;i++){             if (!oldtodos[i].checked) {                 $scope.todos.push({item:oldtodos[i].item,checked:false});             };         }; /*           angular.foreach(oldtodos,function(todo){             if (!todo.checked) {                 $scope.todos.push(todo);             };         }); */               $scope.total = $scope.todos.length;     }; }; //http://jsfiddle.net //http://plnkr.co/ </script> </body> </html> 

in context of example there nothing in particular different between angular.foreach , standard loop.

you don't appear pushing same object $scope.todos in foreach, following help:

angular.foreach(oldtodos, function(todo) {   if (!todo.checked) {     $scope.todos.push({item: todo.item, checked: false});   }; }); 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -