AngularJS指令能否从动态内容中提取类名

Can AngularJS directive pick up class name from dynamic content?

本文关键字:提取 动态 指令 AngularJS      更新时间:2023-09-26

http://jsfiddle.net/xKU5R/

在上面的例子中,我期望cls类的元素在ng-repeat(ng-bind-html-unsafe(中以相同的行为被拾取,并显式地设置一个。

<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!');
            });
        }
    }
});

我想知道我在这里做错了什么?

问题是Angular没有编译新的HTML。最简单的解决方案可能是使用$compile服务手动编译动态内容。在自定义指令中执行此操作,并将ng-bind-html-unsafe="r.alink"替换为类似htmlinsert="r.alink"的内容。以下是该指令的编码方式:

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

对html字符串的引用使用隔离范围绑定传递,然后在附加到重复DOM元素的当前迭代之前进行编译。

演示:http://jsfiddle.net/sh0ber/CLEqc/