How to use the directive in AngularJS

I am taking the first steps with AngularJS directives, and this directive does not work for me.

I have an ng-repeat list

 <ul ng-after-list-filter> <li ng-repeat="item in items | filter:activeFilter.filterType = activeFilter.filterValue">...</li> </ul> 

which is filtered using $scope.activeFilter.filterValue

I am trying to create the ng-after-list-filter directive so that it runs after the list has been filtered, so I can manipulate the dom with this new ul element.

This is my directive that does not work:

 myModule.directive('ngAfterListFilter',function(){ return { restrict: 'A', link: function(scope,element,attrs) { scope.$watch(scope.activeFilter.filterValue, function(val) { console.log('do something here'); }); } } }); 
  • How can I make it work? I assume that scope.activeFilter.filterValue is not updated, but - it is in scope and it becomes updated and the list gets filtered. and I'm trying to look at this variable, so why doesn't it work?

  • Is there a better way to create this directive? I mean - I want to start DOM changes when updating the list (adjust the size of things). so is there a way to listen to $('ul').html() ? I tried this, but it gives me an error that I put the source code in javascript

+3
source share
2 answers

$ last can be used to determine when the last <li> is created. See this script (I did not write it) for the implementation of the checkLast directive, which you can attach to the <li> element:

 directive('checkLast', function () { return function (scope, element, attrs) { if (scope.$last === true) { element.ready(function () { // manipulate ul here, or if that doesn't work // try with $timeout: // $timeout(function() { // do manip here //}, 0, false); // remove false if you need $apply to run 

See also fooobar.com/questions/1452609 / ...

I'm not sure if element.ready () is required, or if it works with dynamically generated elements.

+7
source

It seems you want to reuse the filtered values ​​from the filter? Right?

If you only need to do this:

 <!-- initial filter --> <ul ng-after-list-filter> <li ng-repeat="item in filteredData = (items | filter:activeFilter.filterType)">{{item}}</li> </ul> <!-- reuse what you filtered --> <div ng-repeat="item in filteredData">{{item}}</div> 

I wish I could take advantage of this, but this is a trick I saw in another StackOverflow question that I cannot find now.

Then, to find out when this was updated, you will look at filteredData in the area:

 myModule.directive('ngAfterListFilter',function(){ return { restrict: 'A', link: function(scope,element,attrs) { scope.$watch('filteredData', function(val) { console.log('do something here'); }); } } }); 
0
source

All Articles