1

我正在尝试对指令中的嵌入文本应用过滤器,但我不确定执行此操作的最佳方法是什么。想法的工作副本在以下链接中,但我觉得我正在通过使用编译功能来获取嵌入文本来分类作弊。请参阅JSFiddle

angular.module("MyApp").directive('highlighter', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            phrase: '@',
            text: '@'
        },
        template: '<span ng-bind-html-unsafe=" text | highlight:phrase:false "></span>',
        compile: function (elem, attr, transclude) {
            transclude(elem, function (clone) {
                // grab content and store in text attribute
                var txt = clone[0].textContent;
                attr.text = txt;
            });
        }
    };
});
4

1 回答 1

1

我猜其他方法是http://jsfiddle.net/3vknn/

angular.module("MyApp").directive('highlighter', function () {
    return {
        restrict: 'E',
        scope: {
            phrase: '@'
        },
        controller: function($scope, $filter) {
            $scope.highlight = $filter('highlight');
        },
        link: function (scope, elem, attr) {
            scope.$watch('phrase', function(phrase) {
                var html = scope.highlight( elem.text(), phrase );
                elem.html( html );
            });
        }
    };
});
于 2013-04-26T06:01:59.260 回答