AngularJS - ng-click in directive's link function

人走茶凉 提交于 2019-12-12 02:14:23

问题


I'm working on a directive, and in the link function, while iterating over a array model, want to append elements to the page with ng-click handlers attached to them. Something like this:

app.directive('foo', function(){
   restrict: 'A',
   link: function(scope, elem){
      ... // some logic

      for (var i = 1; i < numberOfPages + 1; i++) {
         elem.append('<li ng-click="bar('+i+')">'+i+'</li>');
      }
   }
});

But the ng-click handlers are dead on arrival. How can I make the handlers behave as expected?


回答1:


In AngularJS, you can't really append directives to your custom directive without having to do some weird $compile logic to get the ngClick directives to register. Probably something like:

// include $compile
// ... append li elements
scope.$apply(function() {
  $compile(elem)(scope);
});

I have no idea if that works by the way, so don't hold me accountable if it doesn't. Generally, the way you solve this problem is with a directive that looks like this:

angular.directive('pager', function() {
  return {
    restrict: 'AEC',
    scope: {
      numPages: '=pager',
      pageFn: '='
    },
    template: '<ul><li ng-repeat="page in pages" ng-click="executePage(page)">{{page}}</li></ul>',
    link:  function(scope, elem, attrs) {
      scope.pages = [];
      scope.$watch('numPages', function(pages) {
        if(!pages) return;
        scope.pages = [];
        for(var i = 1; i <= pages: i++) {
          scope.pages.push(i);
        }
      });
      scope.executePage = function(page) {
        if(scope.pageFn){
          // Additional Logic
          scope.pageFn(page);
        }
      };
    }
  };
})

Then in your html you would write the directive like this:

<my-directive>
  <div pager="numberOfPages" page-fn="goToPage"></div>
</my-directive>

goToPage is a function that is defined in the myDirective directive and accepts a page parameter. At this point, the paging directive is also abstract enough for you to use in multiple places and not really have to worry about external functionality.




回答2:


This should do it:

    app.directive('foo', function($compile){
   restrict: 'A',
   link: function(scope, elem){
      ... // some logic

      for (var i = 1; i < numberOfPages + 1; i++) {
         elem.append('<li ng-click="bar('+i+')">'+i+'</li>');
    $compile(elem)(scope);
      }
   }
});



回答3:


What I've ended up doing is replacing ng-repeat in the directive's template with bindonce, which minimizes the footprint.

https://github.com/Pasvaz/bindonce



来源:https://stackoverflow.com/questions/23135442/angularjs-ng-click-in-directives-link-function

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