我想知道如何做的工作这个片段:
//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 } }; });
我知道这是关于编译阶段
但我没有得到点,所以一个简短的解释是
非常感谢。
提前致谢。
将另一个伪指令添加到同一元素的伪指令:
原文链接:https://www.f2er.com/angularjs/146305.html类似答案:
> How to get ng-class with $dirty working in a directive?
> creating a new directive with angularjs
这是一个plunker: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); }; } }; });
更清洁的解决方案 – 不使用ng点击所有:
管道: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); }); }; } }; });