2

Got a little situation here. I'm just learning Angular and I'm stuck with the following problem.

I've a list that repeats itself (ng-repeat) and when it is rendered, you can click on it and I add a class to the list-item you clicked on, jQuery-style:

$('#'+id).addClass("myClass");

And the id is stored in a scope-variable.

But when I change the scope for the list-item, new items are loaded, and when I change them back to the state were I started, I'm trying to add the class to the same id, but doens't work.

Do I miss something?

Thanks in advance

Kevin Gorjan
  • 1,272
  • 1
  • 17
  • 34
  • It's a mistake to continue with your jQuery mindset when moving on to angular. Think in terms of manipulating your data, rather than manipulating the DOM. See http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1 – Jonathan Wilson Jun 25 '14 at 07:51
  • Thanks for the info. Like I said, I'm still learning and coming from a jQuery background, thought is was possible. – Kevin Gorjan Jun 25 '14 at 07:59

2 Answers2

1

A better approach here would be to alter your data on click and then to conditionally attach a class based on the data:

    <div ng-repeat="item in items" ng-class="{myClass:item.changed}">
      {{item.name}} 
      <button ng-click="item.changed = !item.changed">Change me!</button>
    </div>

Here it is in action: http://jsfiddle.net/wilsonjonash/NTpLS/

As I mentioned in the comments, when programming in angular, think in terms of your model first. Most things you would achieve in jQuery-land with DOM manipulations can be achieved in angular with model-dependent markup (directives).

Best of luck!

Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36
0

You can use the ng-class instead of addClass : )

ngClass Document

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31