Angularjs, Unable to set dropdown from database returned by json object

I have a dropdown of clients with nested json and storing the selected client json object in the database and getting it in the same format. Now when I have returned the selected client model with the restored json object, the client drop will not be selected for this new one and the drop will remain unselected. Please find the plunker at http://plnkr.co/edit/raUmvLDlgFbj1vHRlGeu?p=preview .

<select ng-model="myCustomer" ng-options="customer.name for customer in customers" >
 </select>  

      

Here I am storing myCustomer in the database in the same format. After fetching, I put back a json object (here sampleCustObj). But the dropdown remains unselected even though myCustomer is assigned to sampleCustObj. How can I make a dropdown menu using sampleCustObj?

+3


source to share


1 answer


NgModel will compare objects by reference and not by value, so by setting $scope.myCustomer

on a retrieved object, the object will not appear as selected. from the AngularJS docs:

Note: ngModel is compared by reference, not by value. This is important when binding to an array of objects. See example at jsfiddle .

what you can do is find the index of your retrieved object in the array and a reference to the obeject at that index in the array. The relevant modified lines from you Plunker are listed below:



var sampleCustObj =    {
    "paidCust": false,
    "id": 17884,
    "selected": false,
    "carrierId": 0,
    "name": "----Grteole Group",
    "value": "CU17884",
    "children": [],
    "type": "CUST"
  };

  var fetchedObj = sampleCustObj; //fetch from DB
  var index = $scope.customers.map(function(x) {return x.id; }).indexOf(fetchedObj.id);
  $scope.myCustomer = $scope.customers[index];// Find fetched object in customer array

      

You can also find a working example in this Plunker

+4


source







All Articles