有棱角的如何在tagName中使用变量

Angular. How can I use variable in tagName

本文关键字:tagName 变量      更新时间:2023-11-19

我是angular的新手,我写了一个简单的代码,但它不起作用。有人能解释我如何从输入值中获得tagName吗。这是一个示例,当然我想在数据模型中分配这个变量,所以文本应该是I、B、U或div class="something",但我想随时更改它。

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

工作演示

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允许您设置模型的默认值,因为在这种情况下值("b")不起作用。

<input ng-init="customTag='u'" type="text" ng-model="customTag" placeholder="Enter a name here" ng-change="update()"/>
<span render="{{customTag}}"></span>