Angular select ngChange获取父json对象键而不是值

时间:2015-04-15 14:56:49

标签: angularjs

我创造了一个假设的例子;因为我无法与大家分享我的真实榜样。所以请原谅我创建的草率json文件。

解决问题。假设我使用包含一系列(US State)对象的json文件来填充这样的选择:

State.json

{ "states": 
   [
        {
          code: "AL",
          name: "Alabama"
        },
        {
          code: "AK",
          name: "Alaska"
        },
        {
          code: "AS",
          name: "American Samoa"
        },
        {
          code: "AZ",
          name: "Arizona"
        },
        {
          code: "AR",
          name: "Arkansas"
        },
        {
          code: "CA",
          name: "California"
        },
        {
          code: "CO",
          name: "Colorado"
        },
        {
          code: "CT",
          name: "Connecticut"
        },
        ... etc...


]}

我拉入json文件并将其设置为范围项,如下所示:

主要-controller.js

app.controller('MainCtrl', function ('$scope') { 
  $scope.states = [
    { code: "AL": name: "Alabama" },
    //etc
  ];

  $scope.selectStateChange = function (stateCode) {
      console.log(stateCode);
  }
});

的index.html

这是我的选择:

<select ng-model="selectedState" ng-change="selectStateChange(selectedState)">
    <option ng-repeat="state in states">{{state.name}}</option>
</select>

我的问题

如何在我的ng-change中将实际的状态代码传递给函数selectStateChange?

2 个答案:

答案 0 :(得分:4)

您应该尝试使用ng-options代替ng-repeat on选项。

这样您的模型将是最新的,访问所选对象将非常方便。

在您的情况下看起来应该是这样的:

<select ng-model="selectedState" ng-options="state.name for state in states" ng-change="selectStateChange()">
</select>

你的JS应该显示你的对象:

app.controller('MainCtrl', function ('$scope') { 
  $scope.states = { "AL": "Alabama",  //etc }
  $scope.selectedState = null;

  $scope.selectStateChange = function () {
      console.log(selectedState);
  }
});

这样,selectedState等于{           代码:&#34; AL&#34;,           名称:&#34;阿拉巴马州&#34;         }

答案 1 :(得分:0)

console.log(状态代码)登录到控制台的内容;?

你试过吗

  $scope.selectStateChange = function (selectedState) {
      console.log(selectedState.code);
  }