ng-repeat inside of a directive not having directive functions applied to it

ε祈祈猫儿з 提交于 2019-12-11 11:17:14

问题


I'm trying to basically wrap isotope inside an angular directive. The isotope plugin is being called for .card's a, b, and c, but none of the d's. How can I get all the .card's from the ng-repeat to have the isotope directive applied to them?

<div id="cardHolder" isotope>
  <div class="card">a</div>
  <div class="card w2">b</div>
  <div class="card">c</div>
  <div class="card" ng-repeat="user in users">d</div>
</div>

directive

angular.module('web').directive('isotope', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, fn) {

      $(element).isotope({
        itemSelector: '.card',
        layoutMode: 'fitRows',
      });

    }
  };
});

I found this but it doesn't seem to do anything for my situation


回答1:


Set up a $watch (or $watchCollection in this case) on your ng-repeat items and have it initialize the Isotope container once the browser renders. If any new items appear in scope.users, have the container reload/redraw with the new items included:

.directive('isotope', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, fn) {
      var init;
      scope.$watchCollection('users', function(val){
        $timeout(function(){
          if(!init) {
            $(element).isotope({
              itemSelector: '.card',
              layoutMode: 'fitRows'
            });
            init = true;
          } else {
            $(element).isotope('reloadItems').isotope();
          }
        });
      });  
    }
  }
});

Plunker Demo




回答2:


I am beginner with angularjs. Once I have the same issue with customSelect jquery plugin.

I have solve it using $timeout(angular's setTimeout()).

For you it will looks like this:

app.directive('isotope', ['$timeout', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, fn) {
            $timeout(function() {
                $(element).isotope({
                    itemSelector: '.card',
                    layoutMode: 'fitRows'
                });
            }, 0);
        }
    };
}]); 

I am sure that reason for such kind of behavior is scopes and reapplying problem of widget/plugin. Isotop doesn't wait for ng-repeat.

There should be more concrete solution for this problem. But for "fast solving" $timeout will help.



来源:https://stackoverflow.com/questions/23744591/ng-repeat-inside-of-a-directive-not-having-directive-functions-applied-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!