RoD RoD - 1 month ago 9
AngularJS Question

Change state of variable defined in ng-repeat in controller

I'd like to know whether it's possible to change the value of a variable defined in ng-repeat from the controller or not ?

I'm trying to initialize a simple variable "opened" used for toggling in a ng-repeat, inside the controller.

<div ng-repeat="item in list">
<input type="checkbox" ng-model="active[$index]" ng-click="active[$index]?opened=true:''" />
<a href ng-click="opened=!opened"><span class="glyphicon" ng-class="opened ? 'glyphicon-triangle-bottom' : 'glyphicon-triangle-right'"></span></a>
{{item.title}}
<span ng-show="opened">{{item.title}}</span>
</div>


Here is a plunker showing an example.
http://plnkr.co/edit/lebA2dokhq2W4AsbjKWB?p=preview

Thank you,

Answer

Simple answer is no, because your controller doesn't have access to that scope.

The $scope object you can access from your controller is your "root" scope. Directives like ng-repeat create their own child scopes, which "inherit" their ancestors, meaning they can access their variables. Parent scopes can't access child scopes.

However, there is a trick for that.

You have to define your variable on your root scope (on your controller) and then you can define new properties inside your ng-repeat scope.

like this:

<div ng-repeat="item in list">
    <input type="checkbox" ng-model="active[$index]" ng-click="active[$index]?opened=true:''" />
    <a href ng-click="option.opened=!option.opened"><span class="glyphicon" ng-class="option.opened ? 'glyphicon-triangle-bottom' : 'glyphicon-triangle-right'"></span></a>
    {{item.title}}  
    <span ng-show="option.opened">{{item.title}}</span>    
</div>

In your controller, make sure to create this object: $scope.options = {}