NG-点击后没有编译NG绑定,HTML工作 [英] ng-click not working after compile ng-bind-html
问题描述
我有一个指令
app.directive("dir", function($compile, $sce){
return{
restrict: "E",
link: function(scope, element, attr){
scope.$watch('content',function(){
var html = $sce.trustAsHtml(attr.content);
scope.alabala = $compile(html)(scope);
},true);
},
template: "<div ng-bind-html='alabala'></div>",
}
});
控制器:
function MainController($scope, $http, customService, $location, $sce, $compile){
$scope.init = function(){
customService.get().success(function(data) {
var html = $sce.trustAsHtml(data);
$("#dir").attr("content", data);
});
};
}
和我的索引页上我有:
<div id="div" ng-controller="MainController" class="pull-right span3" ng-init="init()">
<dir id="dir" ></dir>
</div>
我的自定义的服务回报每一次包含例如不同的HTML
my custom service returns every time a different html containing for example
<button ng-click='click()'>Click me</button>
我所试图做的是每次当我在指令的内容推入一个不同的值来编译它,并把它放在我的HTML和我的控制器处理点击功能。因为我是新来AngularJS我一直在努力解决这个问题了一段时间。请帮助。
What I am trying to do is every time when I push a different value in the content of my directive to compile it and put it in my html and handle the click function from my controller. Because I'm new to AngularJS I have been struggling with this problem for sometime. Please help.
推荐答案
您不需要处理 $ SCE 以满足您的目的。
You don't need to deal with $sce to meet your purpose.
您可以通过你的 HTML
作为字符串的指令。该指令编译后它会工作。
You can pass your HTML
as string to the directive. After compilation in the directive it'll work.
在 HTML
在您需要的指令
<dir id="dir" content="myVal"></dir>
在设为myVal
设置不同的值,控制器
Set different value in myVal
your controller
$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>'; // HTML as string
的指令
myApp.directive('dir', function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, element, attr) {
scope.$watch(attr.content, function() {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
})
检查<大骨节病> 演示 骨节病>
这篇关于NG-点击后没有编译NG绑定,HTML工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!