javascript - Why does $index and "$scope.items[index]" need to be used to handle an item in ng-repeat? -


so starting learn angularjs , have question why need call $index particular function instead of simpler code. code:

<div ng-app="myapp"> <div ng-controller='mycontroller'>     <div ng-repeat="people in peoples">     {{people.name}}         <button ng-click="addone($index)" class="button"> try </button>         {{people.likes}}         <button ng-click="addone()" class="button"> try again </button>         {{people.likes}}      </div> </div> 

js:

 var app= angular.module('myapp',[]);  app.controller('mycontroller', function($scope) {   $scope.peoples=[       {           name: "alek",           age:20,           likes:0       },       {           name: "kevin",           age:20,           likes:0       }       ],    $scope.addone= function(){       $scope.peoples.likes= $scope.peoples.likes+=1   }    $scope.addone= function(index){       $scope.peoples[index].likes+=1   }   }) 

i confused why $scope.addone function not work properly, , why need call $index instead in correctly functioning $scope.addone function. essentially, why must call index instead of using other code, because see no real errors in (though new angularjs, maybe missing something).

(i aware 2 functions pertaining same object, yet deleting addone function , having addone function not fix problem hitting button still not raise count).

you not need to, in case need pass object person , work on it.

i.e

$scope.addone= function(people){    people.likes += 1;    //or without passing people can below, here child scope of ng-repeat     //this.people.likes += 1; } 

and

<button ng-click="addone(people)" class="button"> try again </button> 

when $scope.peoples.likes = $scope.peoples.likes+1 not going work because not updating likes property of person, instead (creating and) updating likes property on array peoples.

 var app = angular.module('myapp', []);     app.controller('mycontroller', function($scope) {     $scope.peoples = [{         name: "alek",         age: 20,         likes: 0       }, {         name: "kevin",         age: 20,         likes: 0       }],         $scope.addone = function(people) {           people.likes += 1       }       $scope.addone = function(index) {       $scope.peoples[index].likes += 1     }   })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>  <div ng-app="myapp">    <div ng-controller='mycontroller'>      <div ng-repeat="people in peoples">        {{people.name}}        <button ng-click="addone(people)" class="button">try again</button>        {{people.likes}}        </div>    </div>


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -