【问题标题】:AngularJS - Run custom directive after ng-bind-htmlAngularJS - 在 ng-bind-html 之后运行自定义指令
【发布时间】:2015-05-05 14:19:06
【问题描述】:

我有一个场景,我想在 ng-bind-htmlcreate 的 DOM 上运行自定义指令。

基本上,我必须自定义 html 标记 <a> 的行为,因为正在加载的 html 是不安全的,当用户单击链接时,我必须在发生任何事情之前执行一些功能,也就是 click jqLit​​e的事件。

所以我最初的想法是创建一个指令来修改任何<a> 在我放置指令属性的容器内的行为。

这很好用,直到我与ng-bind-html 结合使用,我的指令在ng-bind-html 将字符串编译成html 并附加到DOM 之前运行。

那么,有什么方法可以在 ng-bind-html 运行之后运行我的自定义指令?

【问题讨论】:

    标签: javascript html angularjs angularjs-directive


    【解决方案1】:

    DEMO

    HTML:

    <div ng-app="myApp" ng-controller="myCtrl">
           <div ng-bind="sometext" my-directive>before</div>
        </div>
    

    控制器:

    angular.module('myApp', []);
    
    angular.module('myApp').controller('myCtrl', function($scope) {   
       $scope.sometext="stuff here";
    });
    

    指令:

    angular.module('myApp').directive('myDirective', function() { 
            return {
                priority: 10, // adjust this value ;)
                link: function(scope,element,attrs) {
                    scope.$watch(attrs.ngBind, function(newvalue) {
                      console.log("element ",element.text());
                    });           
                }
            };      
        });
    

    在指令中使用priority 属性在mg-bind 之后运行您的代码

    【讨论】:

    • 嗯..我没想到$watch函数....我做了this小提琴。我正在考虑的另一件事是.. 我需要注意解除作用域 $destroy 上的 click 事件的绑定?
    • 范围销毁的 Angular 文档暗示您确实需要删除 DOM 事件。 docs.angularjs.org/api/ng.$rootScope.Scope#$destroy
    • 感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多