我正在为一个用例开发一个片段,但是为了保持简单,我进行了一个基本的multiple
转换练习。
问题在于,当一个指令通过绑定动态切换select的multi属性时,ngModel
为null
预期行为
Expected Got Select and option: ngModel: [1] ✓ | ngModel: 1 ✓ multiple = false [option] [ 1 •] [ 2 ] [ 3 ] Expected Got Select and option: ngModel: [1, 3] ✓ | ngModel: null ✕ multiple = true [option] [ 1 •] [ 2 ] [ 3 •]
这个想法很简单,(再次)我有一个按钮,可以切换一个布尔变量,以便在选择中切换多属性。我基于这些答案来制定指令,因为人们认为这是一种更好的方法,那么为什么不呢?
我引用了这些帖子:
-Conditional multiple input file with AngularJS
-Conditional multi-select directive in AngularJS
-Conditionally add the multiple attribute to UI Select
主要问题是,当选择不是ngModel
时,我的multiple
可以很好地工作,但是当它切换并且我选择了多个元素时,它变成了null
。
您有没有想过这个愚蠢的简单方法,或者我应该采用ngIf
方法并保持理智与和平?
app.js:控制器
module.controller("myController", function($scope) {
$scope.options = [1, 2, 3, 4, 5, 6];
$scope.selected = [];
$scope.multiple = false;
$scope.print = function() {
console.log({ seleccion: $scope.selected, multiple: $scope.multiple});
};
$scope.toggleMultiple = function() {
$scope.multiple = !$scope.multiple;
}
$scope.onChange = function(item) {
console.log(item)
$scope.print();
}
});
app.js:指令
module.directive('ngMultiple', function () {
return {
restrict: 'A',
scope: {
ngMultiple: '='
},
link: function (scope, element, attr) {
var unwatch = scope.$watch('ngMultiple', function (newValue) {
if (newValue) {
element.attr('multiple', 'multiple');
} else {
element.removeAttr('multiple');
}
});
}
};
});
index.html
<div ng-app="myModule">
<div ng-controller="myController">
{{message}} <br />
<select name="blabla"
ng-model="selected" id="blabla"
ng-multiple="multiple"
ng-options="o as o for o in options"
ng-change="onChange(selected)">
</select>
<p>{{selectModel.selection}}</p>
<p><button ng-click="print()">Print()</button></p>
<p><button ng-click="toggleMultiple()">Toggle Multiple</button></p>
</div>
</div>