javascript - 从指令生成的 html 范围内调用函数?

标签 javascript html angularjs

我制作了一个使用 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 来演示它:

http://plnkr.co/edit/nckqny1FNiJJjthmlSh8?p=preview

最佳答案

当您动态添加 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/

相关文章:

javascript - AngularJs 上的数据刷新

javascript - AngularJS:编译指令的输出

javascript - 正则表达式如果字符串包含 E 或 F 字母

html - float div 留有 50vw

java - 让 RestAssured 测试与 Spring Security CSRF for AngularJS 一起使用

php - 表单在 Laravel 5 中显示为纯文本

html - 谁压缩他们的 HTML?

javascript - 从id中删除表内容

javascript - 如何使用axios等待文件上传

javascript - 两个脚本之间的jquery冲突