有角度的.如何在tagName中使用变量 [英] Angular. How can I use variable in tagName
问题描述
我对angular并不陌生,我编写了一个简单的代码,但是它不起作用.有人可以解释一下我如何从输入值中获取tagName.这是一个示例,我当然想在数据模型中分配此变量,因此文本将位于I,B,U或div class ="something"中,但我想即时更改它.
I am new to angular and I wrote a simple code, but it doesn't work. Can someone explain me how can i get a tagName from input value. It's a sample, of course I want to assign this variable in data model, so text would be in I, B, U, or div class="something", but I want to change it on the fly.
<div ng-app>
<div>
<input type="text" ng-model="customTag" placeholder="Enter a name here" value="b">
<{{customTag}}>77</{{customTag}}>
</div>
</div>
推荐答案
我认为,您可能必须为此编写一个指令.我定义了一个名为render的指令,该指令监视 customTag
模型以更新DOM.
I think, you may have to write a directive for the same. I've defined a directive named, render which watches the customTag
model to update the DOM.
myApp.directive('render', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('render', function(value) {
if (value) {
element.html('<' + value + '>77</' + value + '>');
} else {
element.html(77);
}
});
}
};
});
最后按如下所示使用它. ng-init
允许您设置模型的默认值,因为value("b")在这种情况下不起作用.
Finally use it as shown below. ng-init
allows you to set the default value for the model as value("b") does not work in this case.
<input ng-init="customTag='u'" type="text" ng-model="customTag" placeholder="Enter a name here" ng-change="update()"/>
<span render="{{customTag}}"></span>
这篇关于有角度的.如何在tagName中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!