use*_*er1 11 html javascript jquery angularjs angularjs-directive
我有一个指令
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>",
}
});
Run Code Online (Sandbox Code Playgroud)
控制器:
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);
});
};
}
Run Code Online (Sandbox Code Playgroud)
在我的索引页面上我有:
<div id="div" ng-controller="MainController" class="pull-right span3" ng-init="init()">
<dir id="dir" ></dir>
</div>
Run Code Online (Sandbox Code Playgroud)
每次包含不同的html时,我的自定义服务都会返回
<button ng-click='click()'>Click me</button>
Run Code Online (Sandbox Code Playgroud)
我想要做的是每当我在我的指令的内容中推送一个不同的值来编译它并将它放在我的html中并从我的控制器处理click函数时.因为我是AngularJS的新手,所以我一直在努力解决这个问题.请帮忙.
Rez*_*eza 26
您无需处理$ sce以满足您的目的.
您可以将HTMLas字符串传递给指令.在指令编译后它将起作用.
在HTML你需要的地方directive
<dir id="dir" content="myVal"></dir>
Run Code Online (Sandbox Code Playgroud)
在myVal控制器中设置不同的值
$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>'; // HTML as string
Run Code Online (Sandbox Code Playgroud)
该 directive
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);
}
}
})
Run Code Online (Sandbox Code Playgroud)
检查 Demo
| 归档时间: |
|
| 查看次数: |
17973 次 |
| 最近记录: |