如何在angularjs中添加条件属性?
例如,如果我的组件的绑定设置为true,我只想在multiple
上设置<select>
属性。这意味着如果未给出绑定,则<select>
上不应存在multiple属性。
我找到的唯一解决方案是使用ng-if。
答案 0 :(得分:1)
您可以通过实现指令(aka ng-multiple
)来处理multiple
元素的属性select
来实现此目的。以下代码段实现了此解决方案。但是,您可能希望在directive
内控制模型的状态,一旦multiple
道具生成所选值的数组,non-multiple
将生成单个对象,因此在multiple
和non-multiple
之间切换时可能会出现问题。
angular.module('myApp', [])
.directive('ngMultiple', function () {
return {
require: ['select', '?ngModel'],
restrict: 'A',
scope: {
multiple: '=ngMultiple'
},
link: function (scope, element, attrs, ctrls) {
element.prop('multiple', scope.multiple);
scope.$watch('multiple', function (multiple) {
if(element.prop('multiple') != multiple){
// may be would be convenient change the ngModel
// to [] or {} depending on the scenario
element.prop('multiple', multiple);
}
});
}
};
})
.controller('myController', function ($scope) {
$scope.condition = true;
$scope.myOptions = [];
});
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-controller="myController">
<label>
<input type="checkbox" ng-model="condition" /> multiple?
</label>
<br>
<select ng-multiple="condition" ng-model="myOptions">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
</select>
<br>
<tt>myOptions: {{ myOptions }}</tt>
</div>
答案 1 :(得分:0)
如果布尔condition
为真,则为多个,否则为
<select ng-if="condition" ng-model="some.model" multiple></select>
<select ng-if="!condition" ng-model="some.model"></select>
<select ng-show="condition" ng-model="some.model" multiple></select>
<select ng-hide="condition" ng-model="some.model"></select>
控制器,
$scope.condition = true