A.Sh A.Sh - 8 months ago 63
AngularJS Question

AngularJS - calculate value for each field

I have list of fields(todos) with button on their left. I want to click on one of the buttons so it calculate the value for this specific field.

What I'm getting is that clicking on specific button calculate and show the same result for all the fields

this is what I wrote :

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

and the controller

$scope.edit = function(index){

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

$scope.result = counter;

What am i doing wrong?

Answer Source

Basically result variable of scope you have used for binding is not the same scope variable which has been defined inside controller scope.

Because ng-repeat does work in quite a different way, when it render a DOM by looping through provided collection(here its todos), it creates a new scope for each iteration which is prototypically inherited from it parent scope.

Do use Dot Rule while defining model, so that it would follow prototypal inheritance,

$scope.model = {};

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


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

Other way around to sort this issue out would be using controllerAs approach while defining controller, but in that case you need to get read of $scope & should replace it with this context of controller function.