Ng-click does not work after compiling ng-bind-html

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>", } }); 

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 user service is returned every time another html contains, for example,

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

What I'm trying to do is every time I click a different value in the contents of my directive to compile it, and put it in my html and handle the click function from my controller. Since I'm new to AngularJS, I once struggled with this problem. Please, help.

+11
javascript jquery html angularjs angularjs-directive
Jan 26 '14 at 22:24
source share
1 answer

You do not need to deal with $ sce to achieve your goal.

You can pass an HTML string as a string to a directive. After compilation in the directive, it will work.

In HTML where you will need directive

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

Set a different value in myVal your controller

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

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 Demo

+26
Jan 27 '14 at 6:52
source share



All Articles