Javascript 角度指令,参考模板内的元素内容

Javascript 角度指令,参考模板内的元素内容,javascript,angularjs,Javascript,Angularjs,我试图做一个指令,如果角度表达式是非空的,则有条件地添加换行符。到目前为止,我有: // this will show text with a <br> conditionally if the text is non-blank angular.module('myApp.directives').directive('brIf', function () { return { scope: { text: '=' }

我试图做一个指令,如果角度表达式是非空的,则有条件地添加换行符。到目前为止,我有:

// 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>'
    };
});
//如果文本非空,则有条件地显示带有
的文本 角度.module('myApp.directives')。指令('brIf',函数(){ 返回{ 范围:{ 文本:'=' }, 模板:“{text}}
” }; });
如果我这样使用它(地址的任何部分可能未定义或为空):


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

<!-- 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>

{{address.number}{{address.street}{{{address.apt}}
…以避免所有字符串数学和text=属性。我知道我可以在指令中编写一个link函数,通过元素参数(我想?)获取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>'
    };
});
//如果文本非空,则有条件地显示带有
的文本 角度.module('myApp.directives')。指令('brIf',函数(){ 返回{ 范围:{ 文本:'=' }, 链接:函数(范围、elm、属性、ctrl){ //我想在这里使用elm的文本,而不是“文本” //在我下面的模板中。这可能吗? }, 模板:“{text}}
” }; });
您可以使用:

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

var interpolationFn = $interpolate(clone[0].innerHTML);
var interpolatedString = interpolationFn(scope);
scope.text = interpolatedString;
或者简单地说:

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

演示:

在大多数情况下,您不需要完整的
转换fn
。如果您在指令选项中设置了
transclude:true
,则只需将
ng transclude
添加到您希望添加内容的模板中即可:

<div class="example" style="background: blue; height: 30px; width: 30px" ng-transclude></div>


参考资料:

@EdgarMartinez-你能详细说明一下吗?我正在阅读关于它的ng文档,但似乎没有得到我需要的(还尝试了$compile在一个指令控制器函数中,运气不太好)。很好的解释!天哪,我花了24小时试着自己完成这项工作,试着解析、评估和转移。下一步我打算试试fluxCapacitor!非常感谢。我看到它在plunker中工作,但在我的项目中,没有骰子。我可以看到scope.text在调试器中正确设置,但当我检查最终呈现时,它看起来是空的,如:
。无论我在标签里放了什么,这种情况都会发生。知道我的项目有什么不同吗?有没有异步加载?试试这个:是的,就是这样。非常感谢。但我猜scope param是父作用域??它似乎在指令的实例之间共享,使得多个br if标记与最后一个相同。我将进一步介绍您的实现,看看是否可以在每个实例专用的作用域上设置变量。添加
scope:true
将解决这一问题:
var interpolationFn = $interpolate(clone[0].innerHTML);
var interpolatedString = interpolationFn(scope);
scope.text = interpolatedString;
scope.text = $interpolate(clone[0].innerHTML)(scope);
<div class="example" style="background: blue; height: 30px; width: 30px" ng-transclude></div>