I'm developing a snippet for a use case, but trying to keep it simply, I went for a basic multiple
switching exercise.
The problem is that ngModel
is null when select's multiple attribute is switched dynamically by a directive who switches the attribute by a binding:
Expected behaviour
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 •]
The idea is simply, (again) I have a button witch switch a boolean variable so the multiple attribute is toggled in a select. I was based on these answers for making a directive since people suggest is a better approach, so why not?!
I referenced these posts:
- Conditional multiple input file with AngularJS
- Conditional multi-select directive in AngularJS
- Conditionally add the multiple attribute to UI Select
The main problem is that my ngModel
works well when the select is not multiple
, but when it's switched, and I select more than one element, it becames null
.
It's there a approach you have fanced about this silly simple issue or should I go for the ngIf
approach and keep stay in peace with my sanity?
app.js: Controller
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: Directive
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>