AngularJS - 在 ng-bind-html 之后运行自定义指令 [英] AngularJS - Run custom directive after ng-bind-html
问题描述
我有一个场景,我想在 ng-bind-html
创建的 DOM 上运行自定义指令.
基本上我必须自定义 html 标签 <a>
的行为,因为正在加载的 html 是不安全的,当用户单击链接时,我必须在执行任何操作之前执行一些功能发生,也就是 jqLite 的 click
事件.
所以我最初的想法是创建一个指令来修改任何 <a>
在我放置指令属性的容器内的行为.
这很好用,直到我与 ng-bind-html
结合,我的指令在 ng-bind-html
将字符串编译成 html 并附加到DOM.
那么,有没有办法在 ng-bind-html
运行后运行我的自定义指令?
DEMO强>
HTML:
<div ng-bind="sometext" my-directive>之前</div>
控制器:
angular.module('myApp', []);angular.module('myApp').controller('myCtrl', function($scope) {$scope.sometext="这里的东西";});
指令:
angular.module('myApp').directive('myDirective', function() {返回 {priority: 10,//调整这个值;)链接:功能(范围,元素,属性){scope.$watch(attrs.ngBind, function(newvalue) {console.log("元素",element.text());});}};});
在指令中使用 priority
属性在 mg-bind 之后运行您的代码
I've a scenario which I want to run a custom directive on the DOM that ng-bind-html
create.
Basicly I've to customize the behavior of the html tag <a>
because the html that is loading is unsafe and when the user click the link I've to execute some functions before anything happens, aka, the click
event of jqLite.
So my original ideia was create a directive that modifies the behavior of any <a>
inside the container that I put the attribute of my directive.
This works fine, until I combine with ng-bind-html
, my directive runs before the ng-bind-html
compile the string into html and attached to the DOM.
So, is any way to run my custom directive after the ng-bind-html
run?
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-bind="sometext" my-directive>before</div>
</div>
Controller:
angular.module('myApp', []);
angular.module('myApp').controller('myCtrl', function($scope) {
$scope.sometext="stuff here";
});
Directive:
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());
});
}
};
});
Use priority
property inside directive to run your code after mg-bind
这篇关于AngularJS - 在 ng-bind-html 之后运行自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!