我制作了一个使用 element.html() 来设置 html 的指令。在该 html 代码中,我希望能够在使用该指令的范围内调用函数。如下所示:
app.directive('myDirective', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
link: function(scope, element) {
element.html('<button ng-click="doit()">Does not work</button>');
}
};
}]);
但 doit() 函数从未被调用。
我做了一个 plnkr 来演示它:
最佳答案
当您动态添加 HTML 时,您必须使用 $compile 服务手动编译和链接它:
app.directive('myDirective', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function(scope, element) {
var e = angular.element('<button ng-click="doit()">Works Now!!</button>');
element.append(e);
$compile(e)(scope);
}
};
}]);
关于javascript - 从指令生成的 html 范围内调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25176028/