AngularJS - 在NG-点击指令的链接功能 [英] AngularJS - ng-click in directive's link function

查看:94
本文介绍了AngularJS - 在NG-点击指令的链接功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作指令,并在链接功能,在遍历一个阵列模式,要追加元素到页面 NG-点击处理器重视他们。事情是这样的:

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>');
      }
   }
});

NG-点击处理程序是在抵达时已经死了。我怎样才能使处理器像预期的那样?

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

推荐答案

在AngularJS,你不能真正附加指令,以您的自定义指令,而不必做一些奇怪的 $编译逻辑来获得 ngClick 指令注册。大概是这样的:

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);
        }
      };
    }
  };
})

然后在你的HTML,你会写指令是这样的:

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

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

GotoPage记述是在 myDirective 指令定义并接受页面参数的函数。在这一点上,分页指令也够抽象,为您在多个地方使用,并没有真正担心外部功能。

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.

这篇关于AngularJS - 在NG-点击指令的链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆