AngularJS的动态属性

amc*_*dnl 12 angularjs

在某些情况下,我需要根据模型中的属性将不同的属性应用于节点.

例如,在一种情况下,我需要添加"必需"标签,而在另一种情况下则不需要.我一直在使用ng-if和不同的分支来完成这个任务,但案件很快就会失控.

 <div ng-if="model.required">
    <input class="form-control"
           type="text"
           required 
           ng-model="model" />
 </div>
 <div ng-if="!model.required">

    // as different options arise,
    // i have more forks for each attribute combo

    <input class="form-control"
           type="text"
           ng-model="model" />
 </div>
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法将属性动态应用于节点?

Mat*_*Way 13

我已经快速创建了一个允许您动态指定属性的指令.

http://jsfiddle.net/HB7LU/1806/

我不确定它是否会以这种简单的形式产生你想要的效果,但它可能是一个很好的起点.你基本上使用:

<div dyn-attrs="someModelArray"></div>

并相应地设置您的模型:

$scope.someModelArray = [
    { attr: 'myattribute', value: '' },
    { attr: 'anotherattribute', value: 'val' }
];
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这种方法中使用的属性不能是指令.他们可以,但他们不会被角度编译. (4认同)

Sim*_*lla 5

在这种情况下,最好使用ngRequired:

<input class="form-control" type="text" ng-required="model.required" />
Run Code Online (Sandbox Code Playgroud)