First of all: I am aware of the Angular Multiselect Dropdown module, which I do not want to use! The use case requires a different kind of multiselect, the one that the HTML <select multiple>
allows and I am trying to realize a way to move items around two of those listboxes.
I already developed some code, which should work, but somehow $scope.selected
is not filled with the right content (or at all). By now, I think it should be a problem with the setup of the controller (I am rather new to JavaScript), since going with ng-model
worked with a simpler example.
index.html
<!doctype html>
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="start.js"></script>
</head>
<body>
<div ng-controller="Configurator">
<select multiple ng-model="selected" ng-options="x.name for x in fields">
</select>
</div>
{{selected}}
<button ng-controller="Configurator" ng-click="move() ">Move</button>
<div ng-controller="Configurator">
<select multiple ng-model="selected2" n g-options="x.name for x in chosen">
</select>
</div>
</body>
</html>
start.js
angular.module('demo', [])
.controller('Configurator', function($scope, $http) {
$http.get('http://localhost:8080/fields').
then(function(response) {
$scope.fields = response.data;
console.log(response.data);
});
$scope.selected;
$scope.chosen;
$scope.selected2;
$scope.move = function() {
console.log('function working');
$scope.chosen = $scope.selected.slice();
$scope.fields = $scope.fields.filter(x => !$scope.selected.includes(x));
}
});
Why does the above code not work as I expect? ng-model
should dynamically save the JSONObjects chosen within the multiselect element in the $scope.selected
element, but it's empty everytime I check via console output and the second multiselect is thereby not filled on button click. What am I doing wrong? Is there a scope issue, because I retrieve the elements via http request? Do I have to initialize $scope.selected
as an array or move it to a different scope? Honestly, I am out of ideas and things to google, so I'd appreciate any help.