Can AngularJS directive display class name from dynamic content?

http://jsfiddle.net/xKU5R/

In the above case, I expect elements with the cls class to be similar to the same behavior from ng-repeat (ng-bind-html-unsafe) and explicitly set it.

<div ng-app="appp"> <div ng-controller="Ctrl"> <ul> <li ng-repeat="r in data" ng-bind-html-unsafe="r.alink"></li> </ul> <div class="cls">External</div> </div> </div> function Ctrl($scope) { $scope.data = [ {alink: '<span><a class="cls">One</a></span>'}, {alink: '<span><a class="cls">Two</a></span>'} ]; } angular.module('appp', []) .directive('cls', function() { return { restrict: 'C', replace: true, scope: true, link: function(scope, element, attrs) { element.bind('click', function() { alert('Aha!'); }); } } }); 

I am wondering what am I doing wrong here?

+6
source share
1 answer

The problem is that the new HTML does not compile Angular. The simplest solution would be to manually compile dynamic content using the $compile service. Do this in the user directive and replace ng-bind-html-unsafe="r.alink" with something like htmlinsert="r.alink" . Here is how this directive can be encoded:

 angular.module('appp', []) .directive('htmlinsert',function($compile){ return { scope: { htmlinsert: '=' }, link: function(scope,element,attrs){ var compiledElement = $compile(scope.htmlinsert)(scope); element.append(compiledElement); } } }); 

The link to the html string is passed using the binding of the binding area and then compiled before adding a repeating DOM element to the current iteration.

Demo : http://jsfiddle.net/sh0ber/CLEqc/

+5
source

Source: https://habr.com/ru/post/946555/


All Articles