From inside a custom directive how to change text of another span element?

旧街凉风 提交于 2019-12-11 03:23:23

问题


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

// 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);
        }
    };
});

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.


回答1:


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);
        }
    };
});


来源:https://stackoverflow.com/questions/21652345/from-inside-a-custom-directive-how-to-change-text-of-another-span-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!