ng-options not binding when it has preselected values ng-options not binding when it has preselected values angularjs angularjs

ng-options not binding when it has preselected values


Below implementation might be what you asked for:

HTML:

 <form name="myForm">    <label for="mySelect">Make a choice:</label>    <select name="mySelect" id="mySelect"      ng-options="option.tag for option in post.tag track by option._id"      ng-model="post.selected" multiple></select>      <br>      <button ng-click="updatePost()"> Add Tag</button> </form>

JS:

(function(angular) {  'use strict';  angular.module('defaultValueSelect', [])    .controller('ExampleController', ['$scope', '$http', function($scope, $http) {      var url = "https://jsonblob.com/api/jsonBlob/aa6b4eb4-5284-11e8-a5ee-fd00735e3b38";      var index = 4;      var extraObj = {        tag: "tag",        _id: "5ae410756b7a61080cd17c7"      };      $http        .get(url)        .then(function(response) {          $scope.post = {            tag: response.data,            selected: response.data[0]          };        });      $scope.updatePost = function() {        var tmp = {};        tmp = angular.copy(extraObj);        console.log(angular.copy($scope.post));        tmp.tag += index;        tmp._id += index;        $scope.post.tag.push(tmp);        console.log($scope.post);        index++;      }    }]);})(window.angular);

For working code refer to this plunkr: plnkr.co/edit/cwDRa2Qjg2IlUi5JOAPj


I used angular select documentation as a reference and created a plunker from their example found here.

I used this blob to simulate your data set.

This is what my select directive looks like. I would suggest that you not overwrite the binding for the array with the bind for the selected item, that is what is causing you problems.

(function(angular) {  'use strict';angular.module('defaultValueSelect', [])  .controller('ExampleController', ['$scope','$http', function($scope,$http) {    var url = "https://jsonblob.com/api/jsonBlob/aa6b4eb4-5284-11e8-a5ee-fd00735e3b38";    $http        .get(url)        .then(function(response){            $scope.post = {                tag: response.data,                selected: response.data[0]            };        }) }]);})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><body ng-app="defaultValueSelect">  <div ng-controller="ExampleController">  <form name="myForm">    <label for="mySelect">Make a choice:</label>    <select name="mySelect" id="mySelect"      ng-options="option.tag for option in post.tag track by option._id"      ng-model="post.selected" multiple></select>  </form>  <hr>  <tt>option = {{post.selected}}</tt><br/></div></body>