Use angular directive to change ng-repeat element classes

I am trying to conditionally change the class of an element that is nested in an unordered list.

If you are not using ng-repeat to create a list, I can use the jqlite.children () selector to find the correct item and change the class.

However, I use ng-repeat to create the list, and I cannot figure out how to access the specific element of the list that I want..children () always returns undefined.

here is the jsfiddle of what i am trying to do http://jsfiddle.net/whitehead1415/ENtTC/3/

app.directive('myDirective1', function () { return { restrict: 'A', link: function ($scope, element, attrs, controller) { //for some reason element.children()[0] is undefined //why? what can I do about it? angular.element(element.children()[0]).css('background', 'grey') } }; }); 

I need to change a class based on two things

  • when the user clicks on a specific element, the element should highlight
  • when the user clicks the button, which is the next element, it will be highlighted (this button is not included in jsfiddle)

I was thinking about putting a directive in each element of the list, but the only problem is that I do not know how to make them all aware of each other, so that only one element is highlighted at a time

+6
source share
1 answer

The reason for this is because ng-repeat modifies the DOM template so that children do not exist at the time the directive is compiled. You need to set $watch on element.children() in the directive so that the directive is notified when children are added, and apply CSS at this time. Do this in your link function (which is a postLink function declared as a directory method):

 $scope.$watch(element.children(),function(){ var children = element.children(); for(var i=0;i<children.length;i++){ if(children[i].nodeType !== 8){ angular.element(children[i]).css('background', 'grey'); } } }); 

> $watch also needs to be checked and made sure that nodeType not a comment (type 8 ), because ng-repeat inserts comments that will cause an error if you try to apply CSS.

Screenshot : Here is a working violin

+9
source

Source: https://habr.com/ru/post/945840/


All Articles