Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  89] [ 2]  / answers: 1 / hits: 18336  / 11 Years ago, sun, january 26, 2014, 12:00:00

I have a 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>,
}
});


a controller:



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);

});
};
}


and on my index page I have:



<div id=div ng-controller=MainController class=pull-right span3 ng-init=init()>
<dir id=dir ></dir>
</div>


my custom service returns every time a different html containing for example



<button ng-click='click()'>Click me</button>


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.


More From » jquery

 Answers
26

You don't need to deal with $sce to meet your purpose.



You can pass your HTML as string to the directive. After compilation in the directive it'll work.



In HTML where you need the directive



<dir id=dir content=myVal></dir>


Set different value in myVal your controller



$scope.myVal = '<button ng-click='buttonClick()'>I'm button</button>'; // HTML as string


The 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);
}
}
})


Check the Demo


[#72929] Friday, January 24, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frankiebobbyc

Total Points: 18
Total Questions: 85
Total Answers: 104

Location: Norway
Member since Wed, Jul 7, 2021
3 Years ago
;