3

I have a customer dropdown with nested json and saving the selected customer json object in the data base and retrieving it in the same format. Now when I set back the selected customer model with the retrieved json object, the customer drop is not getting selected to this new one and the drop down remains 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 saving myCustomer in database in the same format. After retrieving, I am assigning the json object back to it (here sampleCustObj). But the dropdown remains unselected even though myCustomer is assigned with sampleCustObj. How can I make dropdown selected with the sampleCustObj?

1 Answer 1

4

NgModel will compare the objects by reference, not by value, so by setting the $scope.myCustomer to the fetched object the object will not show as selected. from the AngularJS docs:

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

what you can do is to find the index of your fetched object in the the array, and the link to the obeject at this index in the array. The relevant modified lines from you Plunker is listed bellow:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.