Chenko47
Chenko47

Reputation: 303

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>

Upvotes: 0

Views: 420

Answers (2)

krutkowski86
krutkowski86

Reputation: 1083

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/

Upvotes: 0

RWAM
RWAM

Reputation: 7018

You are using the controllerAs-Syntax, so you must use vm.arr in your ng-repeat. And furthermore you should use the ng-repeat on the list item:

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

Upvotes: 1

Related Questions