【问题标题】:Can AngularJS directive pick up class name from dynamic content?AngularJS 指令可以从动态内容中获取类名吗?
【发布时间】:2013-05-31 13:08:40
【问题描述】:

http://jsfiddle.net/xKU5R/

在上述情况下,我希望从 ng-repeat (ng-bind-html-unsafe) 中以相同的行为拾取具有 cls 类的元素,并明确设置一个。

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

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

【问题讨论】:

    标签: javascript html angularjs angularjs-directive angularjs-compile


    【解决方案1】:

    问题在于 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/

    【讨论】:

    • 我有点怀疑它与 Angular 的编译功能有关,并且知道指令除了链接之外还有编译。但没有意识到它必须在一个单独的指令中完成,:( 感谢@shOber 的帮助!
    猜你喜欢
    • 2013-12-18
    • 2018-01-09
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多