AngularJS multiselect – passing default values to be selected on load

  angularjs, javascript, multi-select, select

I’m having a problem with multiselect in angularJS. The data flow should look like this:
Global variable -> $scope variable (list of objects) -> ng-options="item.id as item.name for item in items" That works fine. The problem is with data flow of selected values:

ng-model="selected" -> $scope.selected -> $cookies.put("selected", $scope.selected).

Then I retract the value from cookie to $scope.selected by on variable declaration:

$scope.selected = restoreSelectedFromCoookies();
function restoreSelectedFromCookies() {
   const cookieSelected = $cookies.get("selected");
   return angular.isDefined(cookieSelected) ? cookieSelected : [];
}

As for now my select looks like this:

<select 
   ng-options="value.id as value.name for value in items"
   ng-model="selected"
   multiple
   ng-init="selected"
   ng-change="putInCookies()"
></select>

The next step is to put those values into select to have them chosen on page load, so that last picked options are visible on page load. Here is the problem – no idea how to make that. Tried out with ng-selected="selected", tried with ng-init="selected", tried with value="selected". Is there any way of pre-selecting on multiselect? I am also using bootstrap for angular, but I don’t think it’s important here.

Tried to do a jsFiddle, but it does not work there from the very beginning. Guess some kind of unsatisfied dependency, that is in this huge portion of legacy code.

Source: Ask Javascript Questions

LEAVE A COMMENT