Danilo Caro Aparicio
Danilo Caro Aparicio

Reputation: 68

How to load array from select in empty model using angular js?

i have a multiselect (select2 jquery) loaded by array service, then i get some id values from selects and load json array in a empty model.

First, i get empty model from rest api, then i want load internal array from selected values.

my json empty model obtained from service:

{
     "params": [{
          "id": 0,
          "desc": ""
}],
     "person": {
         "name": "",
         "age": 0
   }
}

My controller js:

app.controller('ctrl', ['$scope', function ($scope) {

$scope.emptyModel = {};

$scope.initEmptyModel = function() {
    $scope.emptyModel = getEmptyModelFromService(); //success
}

$scope.getObjectFromCombo = function(data){
   //if i select 3 options, i want load 3 objects in array
   // but "data" contains a int Array and not object :/
   emptyModel.params.id = data.id; 
   emptyModel.params.desc = data.desc;   
}


}]);

my html select:

<div ng-init="initEmptyModel()">

    <input type="text" class="form-control" ng-model="emptyModel.person.name" />  <!--success load value-->
    <input type="text" class="form-control" ng-model="emptyModel.person.age" />   <!--success load value-->


   <select class="form-control" multiple="multiple" ng-model="aux" ng-change="getObjectFromCombo(aux)">
           <option ng-repeat="item in listService" value="{{item.id}}">{{item.desc}}</option>
   </select>

</div>

Upvotes: 0

Views: 87

Answers (1)

Nove Sanchez
Nove Sanchez

Reputation: 109

Try this.

Instead of using the with the ng-repeat change it by using the ng-options directive.

<select class="form-control" multiple="multiple" ng-model="aux" ng-change="getObjectFromCombo()" ng-options="item.desc for item in listServicetrack by item.id"></select>

And in your getObjectFromCombo() function used the $scope.aux. Make sure you declare your $scope.aux as an array.

$scope.getObjectFromCombo = function(){
  //print the content of the aux model
  //this will print an array of object
  console.log($scope.aux); }

Upvotes: 0

Related Questions