gpt4 book ai didi

javascript - Angular 指令,引用模板内部的元素内容

转载 作者:行者123 更新时间:2023-12-03 17:45:00 24 4
gpt4 key购买 nike

我正在尝试制定一个指令,如果 Angular 表达式不为空,则有条件地添加换行符。到目前为止,我有这个:

// this will show text with a <br> conditionally if the text is non-blank
angular.module('myApp.directives').directive('brIf', function () {
return {
scope: {
text: '='
},
template: '<span ng-show="text && text.trim().length">{{ text }}<br/></span>'
};
});

如果我这样使用它会起作用(地址的任何部分都可能未定义或空白):

<br-if text="address.number + ' ' + address.street + ' ' + address.apt"></br-if>

但我真正想要的是一个我可以像这样使用的指令:

<!-- put a br at the end of all this jazz, only if the expression is not blank -->
<br-if>{{address.number}} {{address.street}} {{address.apt}}</br-if>

...避免所有字符串数学和 text= 属性。我知道我可以在我的指令中编写一个链接函数,通过元素参数获取 html 内容(我想?),但我不知道如何在模板中使用该元素的内容。换句话说,在链接函数中查看我的问题...

// this will show text with a <br> conditionally if the text is non-blank
angular.module('myApp.directives').directive('brIf', function () {
return {
scope: {
text: '='
},
link: function(scope, elm, attrs, ctrl) {
// I want the text of elm here to be used instead of 'text'
// in my template below. Is this possible?
},
template: '<span ng-show="text && text.trim().length">{{ text }}<br/></span>'
};
});

最佳答案

您可以使用 transclusion :

app.directive('brIf', function($interpolate) {
return {
restrict: 'E',
template: '<span ng-show="text && text.trim().length">{{ text }}<br/></span>',
transclude: true,
link: function(scope, element, attrs, controller, transclusionFn) {

transclusionFn(scope, function(clone) {

scope.text = $interpolate(clone[0].innerHTML)(scope);
});
}
};
});

您所追求的是clone,它将是您嵌入内容的全新编译副本。这意味着例如 clone[0].innerHTML 将是:

{{address.number}} {{address.street}} {{address.apt}}

然后您可以使用 $interpolate 服务将字符串编译成插值函数,使用此函数根据范围计算插值字符串并使用结果:

var interpolationFn = $interpolate(clone[0].innerHTML);
var interpolatedString = interpolationFn(scope);
scope.text = interpolatedString;

或者简单地说:

scope.text = $interpolate(clone[0].innerHTML)(scope);

演示: http://plnkr.co/edit/VNauZ0Kkr1HLCnsWTgyO?p=preview

关于javascript - Angular 指令,引用模板内部的元素内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com