Angular指令如何向元素添加属性?
我想知道如何使用此代码段:
//html<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users">{{user.name}}</a>
    </div>
</div>
//js
var app = angular.module('app', []);
app.controller("AppCtrl", function ($scope) {
    $scope.users = [{name:'John',id:1},{name:'anonymous'}];
    $scope.fxn = function() {
        alert('It works');
    };
})  
app.directive("myDir", function ($compile) {
    return {
        link:function(scope,el){
            el.attr('ng-click','fxn()');
            //$compile(el)(scope); with this the script go mad 
        }
     };
});
我知道这是关于编译阶段的,但是我不明白这一点,所以简短的解释将是非常感谢。
回答:
将另一个指令添加到同一元素的指令:
类似答案:
这是一个小矮人:http
://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});
更清洁的解决方案-完全不使用ngClick:
矮人:http
://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});
以上是 Angular指令如何向元素添加属性? 的全部内容, 来源链接: utcz.com/qa/410405.html








