如何在 angularjs 中设置的数组中使用 indexof

how to use indexof in array set in angularjs

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = this.drop.state;  }
});
</script>
<body>

<div ng-app="myApp" ng-controller="myctrl">
State : 
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>

在这段代码中,我可以从变量 a 的文本框中获取选定的值。现在,我需要获取所选名称的代码值。是否可以使用 indexof()。 And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

您可以将 code 作为值分配给 option

<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}}

演示

var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.drop = {}
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() { 
            var a = $scope.drop.state
            console.log(a)
    }
});
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl">
State : 
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}} </option>
</select>
</div>

尽管其他答案有效,但这是正确的方法:

<select id="stat" ng-model="drop.state" ng-options="x.code as x.name for x in state" ng-change="onChange()">
  <option value="">Select a value</option>
</select>

如果 ng-change 的目的是获取状态代码,则不需要这种方式。您的 ng-model 将等于所选的州代码。

您可以将数据绑定到单个 属性,并且可以访问两者。首选 ng-options .

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
  var app = angular.module('myApp', []);
  app.controller('myctrl', function($scope) {
    $scope.state = [{
      name: 'TamilNadu',
      code: 1
    }, {
      name: 'Kerala',
      code: 2
    }, {
      name: 'Karnataka',
      code: 3
    }];
    $scope.onChange = function() {     
     alert(this.drop.state.name);  
     alert(this.drop.state.code);  
    }
  });
</script>

<body>

  <div ng-app="myApp" ng-controller="myctrl">
    State :
    <select id="stat" ng-model="drop.state" ng-options= "x as x.name for x in state" ng-change="onChange()"> </select>

</div>
</body>

<option value="{{x}}" ng-repeat = "x in state"> {{x.name}} </option>

如果您在选项上添加值,您可能会得到完整的对象,并访问代码和值