AngularJs: Ng-model object and single model Together

AngularJs: Ng-model object and single model Together

我没有足够的英文来描述它,但我想你会从代码中理解它。 基本上我的问题是 ng-model = "" ng-options = "" 一起使用时没有提供表单数据。

<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>

这些车的品牌选择框

<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>

这是其他表单对象。其中 ng-model 是不同的数据 "data." 我可以得到它。如何获取选择框中的值

我需要获取 "car_id" 值。

试试这个:

  • 更改下拉选项时,将所选值作为参数传递给函数。
  • 使用 array.filter() 方法根据汽车 ID 获取所选汽车的 model year

演示版

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>