0

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>
Chenko47
  • 293
  • 5
  • 10

2 Answers2

1

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>
RWAM
  • 6,760
  • 3
  • 32
  • 45
0

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/

krutkowski86
  • 1,084
  • 9
  • 16