shank
shank

Reputation: 91

ng-repeat not accessing $scope variable

$scope.new is a variable..that i am trying to access in ng-repeat but ng-repeat treats 'new' as a local variable and changes its value within its scope only...i want to give particular index to $scope.new variable...without using functions...thank you....

<html>
<style>
.yoyo{font-size:30px;}
</style>


<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.new=0;
});
</script>

<body>

<div data-ng-app="myApp" ng-controller="customersCtrl" data-ng-init="names=['Jani','Hege','Kai']">
  <p>Looping with ng-repeat:</p>
  <ul>
    <li data-ng-repeat="x in names" ng-click="new=$index" ng-class="yoyo:new==$index">
      {{ x }}{{$index}}{{new}}
    </li>
  </ul>


</body>
</html>

Upvotes: 0

Views: 3005

Answers (1)

Manoj Shevate
Manoj Shevate

Reputation: 742

ng-repeat uses isolated scope, so when you are trying to update new variable inside ng-repeat, its updating the local $scope use $parent.new instead of only new in ng-click directive. refer below working code snippet -

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.new=0;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>

<div data-ng-app="myApp" ng-controller="customersCtrl" data-ng-init="names=['Jani','Hege','Kai']">
  <p>Looping with ng-repeat:</p>
  <ul>
    <li data-ng-repeat="x in names" ng-click="$parent.new=$index" ng-class="yoyo:new==$index">
      {{ x }}{{$index}}{{new}}
    </li>
  </ul>
  
  </div>


</body>

Hope this helps!

Upvotes: 3

Related Questions