从自定义指令内如何改变另一个范围元素的文本? [英] From inside a custom directive how to change text of another span element?

查看:125
本文介绍了从自定义指令内如何改变另一个范围元素的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<输入> 持有我的自定义指令作为一个属性,该属性我给目的地的ID将接收文本中。目前,我正在做使用jQuery的文字变化,但我宁愿使用全角方式......所以这是有约束力的,但是从内心指令还挺。为简单起见,我做我的code的简单草案:
搜索结果HTML code

I have an <input> which holds my custom directive as an attribute and inside that attribute I give the ID of destination that will receive the text. At the moment I am doing the text change with jQuery but I would rather use the full Angular way...So it's kinda of a binding but from within a directive. To make it simple, I made a simple draft of my code:

HTML Code

<input type="text" name="input1" my-directive="message1" />
<span id="message1"></span>

JS code

JS Code

// Angular - custom Directive
directive('myDirective', function($log) {
    return{
        require: "ngModel",
        link: function(scope, elm, attrs, ctrl) {
            var receiverId = attrs.myDirective;
            var whateverText = 'blabla';

            $('#'+receiverId).text(whateverText);
        }
    };
});

使用我的&LT的ID;跨度&GT; 元素可能不是最好的解决办法,但是这是我得到了它使用jQuery。这可能是较好的去除标识,但怎么可能我在跨度更新文本毕竟?而且我们不要忘记,这是一个形式,我们可以有多个输入和span元素。另外请注意,我不想使用控制器来传递文本,它留在指令中,我想重新使用它。
搜索结果请不要告诉我,我不应该做这种方式,我要坚持这种行为。

Using the ID on my <span> element is probably not the best solution, but that is how I got it working with jQuery. It's probably better to remove the ID, but then how could I update the text in my span after all? And let's not forget that it's a Form and we can have multiple input and span elements. Also note that I do not want to use the controller to pass the text, it has to stay within the directive as I want to re-use it.

Please don't tell me that I shouldn't do it this way, I want to stick with this behavior.

推荐答案

如果在&LT;跨度&GT; 将永远是下一个兄弟按照你的榜样,只要使用 elm.next(),因为它是在角本土的 jqLit​​e ,无需使用jQuery包装,如:

If the <span> will always be the next sibling as per your example, just use elm.next() as it is supported in Angular's native jqLite, no need to wrap with jQuery, e.g.

directive('myDirective', function($log) {
    return{
        require: "ngModel",
        link: function(scope, elm, attrs, ctrl) {
            var receiverId = attrs.myDirective;
            var whateverText = 'blabla';

            elm.next().text(whateverText);
        }
    };
});

这篇关于从自定义指令内如何改变另一个范围元素的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆