从自定义指令内部如何更改另一个 span 元素的文本? [英] From inside a custom directive how to change text of another span element?
问题描述
我有一个 <input>
它将我的自定义指令保存为一个属性,在该属性中我给出了将接收文本的目的地 ID.目前我正在使用 jQuery 进行文本更改,但我宁愿使用完整的 Angular 方式......所以它有点像绑定,但来自指令内.为了简单起见,我制作了一个简单的代码草稿:
HTML 代码
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代码
// 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);
}
};
});
在我的 <span>
元素上使用 ID 可能不是最好的解决方案,但这就是我使用 jQuery 的方式.删除 ID 可能会更好,但毕竟我如何更新跨度中的文本?我们不要忘记它是一个 Form 并且我们可以有多个 input 和 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.
推荐答案
如果 <span>
根据您的示例将始终是下一个兄弟,只需使用 elm.next()
因为它在 Angular 的原生 jqLite 中得到支持,无需包装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);
}
};
});
这篇关于从自定义指令内部如何更改另一个 span 元素的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!