javascripthtmlangularjsng-options

AngularJS Select index of selected property


I have a request that returns an array of objects based on a Provider selected. Like this:

data:[
    0:
        Producto:"Chiken",
        Unidad: "box",
        PrecioUnitario:"34334",
        etc..
    1:
        Producto:"Chiken",
        Unidad: "box",
        PrecioUnitario:"200",
        etc..
]

I'm displaying the data properly in a <select> tag Example

What I want is that if the user selects let's say "Carne Asada" all of the other properties of that selected child object are auto-selected on the rest of the fields, i.e:

Unidad text input should be "box" automatically, "precioUnitario" field should be 200. Or visually: enter image description here

Another thing is that it should display the value that the object has but it can be edited by the user.

Controller:

$scope.columns = [{colId: 'col1', producto:[], catidad:'', unidades:[], preunit:''}];
$scope.fact = {};

$scope.get_proveedor_prod = function(fact){
  var data = {ProveedorID: fact.ProvID};
  $http.post(URL + "/api/get_prod_by_provider.php",data).then(function(callback) {
      $scope.products = callback.data;
  }); 
}

View:

<md-input-container>
  <select ng-model="fact.producto"
  ng-options="item.ProductID as item.NombreProducto for item in products"
    class="form-control selectformcc" required>
    <option value="" disabled selected>Producto</option>
  </select>
</md-input-container> 

Solution

  • (I'm assuming your data notation is incorrect and that you meant to use an array of objects.)

    Bind the select to the whole item instead of to a property of the item:

    ng-options="item as item.NombreProducto for item in products"  //not ="item.ProductID...
    

    Now fact.producto (select model) is an object and will contain the whole item. In your Unidad text box you can use:

    <input type="text" ng-model="fact.producto.Unidad" />
    

    Here is an example with easy to understand data: Working Fiddle