Search code examples
angularjsangular-ngmodelangularjs-ng-options

AngularJs: Ng-model object and single model Together


I do not have enough English to describe it, but I think you will understand it from the codes. Basically my problem is that ng-model = "" ng-options = "" does not come up with form data when used together.

<select class="form-control" name="car_id" ng-model="car_id" ng-options="I.car_brand_code as I.car_brand_name for I in CarList" ng-change="GetState()" >
                                    <option value="">Select Car</option>
                                </select>

The selection box for the brands of these cars

<div class="form-group">
                                    <label class="mtb10">Model Year</label>
                                    <input type="text" name="modelYear" class="form-control" ng-model="data.modelYear" placeholder="Car Year...">
                                </div>

This is the other form objects. Where ng-model is a different data "data." I can get it. How can I get the value in the selection box.

I need to get the "car_id" value.


Solution

  • Try this :

    • On change of the dropdown options pass the selected value into the function as a param.
    • Use array.filter() method to fetch the model year for the selected car based on the car id.

    DEMO

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl',function($scope) {
        $scope.CarList = [
          {
          "car_brand_code": 1,
          "car_brand_name": "Maruti",
          "model_year": 1990
          },
          {
          "car_brand_code": 2,
          "car_brand_name": "Ford",
          "model_year": 2005
          }
        ];
        
        $scope.GetState = function(carId) {
          var selectedCar = $scope.CarList.filter(function(item) {
            return item.car_brand_code == carId;
          });
          $scope.data = {
            "modelYear" : selectedCar[0].model_year
          }
        };
        
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
      <select class="form-control" name="car_id" ng-model="car_id" ng-options="I.car_brand_code as I.car_brand_name for I in CarList" ng-change="GetState(car_id)" >
        <option value="">Select Car</option>
      </select>
      <div class="form-group">
        <label class="mtb10">Model Year</label>
        <input type="text" name="modelYear" class="form-control" ng-model="data.modelYear" placeholder="Car Year...">
      </div>
    </div>