Search code examples
angularjsangularjs-ng-repeatng-style

access variable in scope from ng-repeat ng-style


I got some problem on AngularJS. my controller, mainCtrl, has this variables :

this.colors = {Sam:blue,Jane:red,Tom:pink};
this.arr = [{person:'Sam',story:'some story'},{name:'Tom',story:'some story2'}]

And I got this code :

<div ng-controller="mainCtrl as vm">
<ul ng-repeat="obj in arr">
<li ng-style={color:vm.color[obj.person]}>{{obj.story}}</li>
</ul>
</div>

I want that the li will be colored such as the color of the person at colors dictionary . how can I handle that? I got undefined every time, but when I do it explictly its work , for Example :

<li ng-style={color:vm.color['Sam']}>{{obj.story}}</li>

Solution

  • It should look like this.

    <div ng-controller="mainCtrl as vm">
       <ul>
           <li ng-repeat="obj in vm.arr track by $index" 
               ng-style="{'color':vm.colors[obj.person]}"
               ng-bind="obj.story">
           </li>
       </ul>
    </div>
    
    1. Remember to use your alias vm (controllerAs)
    2. Usetrack by with ng-repeat for better performance.
    3. I think that ng-repeat should have been placed in li

    Her's a working jsfiddle http://jsfiddle.net/irhabi/nh4ddemr/