在指令中的转换期间无法传递插值

时间:2018-06-18 21:24:12

标签: angularjs angularjs-directive

我正在创建一个电子邮件指令,如下所示

angular.module('app')
    .directive('email', function () {
        return {
            restrict: 'EA',
            transclude: true,
            template: '<a href="{{email}}">{{email}}</a>',
            link: function (scope, element, attrs, ctrl, transclude) {                
                transclude(scope, function (clone) {
                    scope.email = clone.text();
                });

            }
        };
    });

我在HTML中使用它,如下所示,

<email>{{emailId}}</email>

但是,我无法在指令中传递emailId的插值。该指令的输出结束为,

 <a href="{{emailId}}">{{emailId}}</a>

我们如何在指令中传递实际插值?

Plnkr - http://plnkr.co/edit/AeBfp3VayKihygelKr9C?p=preview

2 个答案:

答案 0 :(得分:0)

要将变量传递给指令范围,只需使用属性:

angular.module('app')
.directive('email', function () {
    return {
        restrict: 'EA',
        ̶t̶r̶a̶n̶s̶c̶l̶u̶d̶e̶:̶ ̶t̶r̶u̶e̶,̶
        template: '<a href="{{email}}">{{email}}</a>',
        link: function (scope, element, attrs, ctrl, transclude) {                
            //transclude(scope, function (clone) {
            //    scope.email = clone.text();
            //});
            scope.email = scope.$eval(attrs.addr);
            //OR
            scope.$watch(attrs.addr, function(value) {
                scope.email = value;
            });
        }
    };
});

用法:

<̶e̶m̶a̶i̶l̶>̶{̶{̶e̶m̶a̶i̶l̶I̶d̶}̶}̶<̶/̶e̶m̶a̶i̶l̶>̶

<email addr="emailId"></email>

无需使用包含来评估角度表达式。

有关详细信息,请参阅

答案 1 :(得分:0)

您只需在元素上添加指令模板ng-transclude即可 这是代码

angular.module('app')
.directive('email', function () {
    return {
        restrict: 'EA',
        transclude: true,
        template: '<a href="{{email}}" ng-transclude>{{email}}</a>',
        link: function (scope, element, attrs, ctrl, transclude) {          
        }
    };
});

这是链接 Plunker http://next.plnkr.co/edit/SY3ih9NwAqz7ZhZg?open=lib%2Fscript.js&preview