Pradeep Pradeep - 2 months ago 8
AngularJS Question

How to update parent model object using angularjs

I am facing a problem with the below code.

<tr ng-repeat="diag in diags track by diag.id">
<td>
<select id="ddTest" ng-change="changeevent()">
<option value="">Select Number</option>
<option ng-repeat="o in orderNumbers" data-diagId="{{diag.id}}" ng-selected="o==diag.ordernumber">{{order}}
</option>
</select>
</td>
</tr>

$scope.orderNumbers= [1,2,3,4,5,6,7,8,9,10];


In
diags
object is an array which contains
ordernumber
in it. I am trying to update the specific
ordernumber
from ddTest dropdown change to the
diags
object using the custom attribute data-diagId. I don't have any model for ddTest dropdown (I can add it if needed). I want to populate the value on load and also need to update the parent object with the new order number selected. Can anybody help me to do this ?

Answer

Use ng-options directive and ng-model in Your select, then diag.ordernumber will change every time select is changed, so selected option is connected to model without any additional programming. Here full working example:

var app = angular.module("diagApp", []); 

app.controller("diagController", function($scope) {
    $scope.orderNumbers= [1,2,3,4,5,6,7,8,9,10];
    
    //test diags
    $scope.diags=[
    {id:1,ordernumber:1},
    {id:2,ordernumber:2},
    {id:3,ordernumber:3}
    
    ];
    
    //to prove that diag is changing
    $scope.change=function(diag){
    
       console.log(diag);
    
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="diagApp">
<table ng-controller="diagController">
<tr ng-repeat="diag in diags track by diag.id">
       <td>
           <select ng-change="change(diag)" id="ddTest" ng-model="diag.ordernumber" ng-options="item as item for item in orderNumbers track by item">
           </select>
      </td>
  </tr>
</table>
</div>

Comments