gpt4 book ai didi

javascript - Angular : Get the index of the dropdown item

转载 作者:行者123 更新时间:2023-11-30 10:01:50 24 4
gpt4 key购买 nike

我的观点如下

<div>
<select ng-model="obj.arr[otherObj.variable]" ng-change="otherObj.variable=SOMETHING">
<option ng-repeat="label in obj.arrs">{{label}}</option>
</select>
</div>

没有 ng-change 属性,当 otherObj.variable 是 obj.arr 的索引之一时,此代码会执行我想要的操作 - 它会选择正确的项目在列表中。

除此之外我想要的是将 otherObj.variable 设置为下拉变量更改时选择的数组项的索引。因此,如果选择下拉列表中的第二个值,则 otherObj.variable 应设置为 1。我尝试使用

ng-change="otherObj.variable=SOMETHING"

问题是,我不知道 SOMETHING 应该是什么。我这样做对吗?

编辑

我的要求是

  1. 默认选择下拉列表中的顶部选项
  2. 根据 otherObj.variable 的值在数组中选择适当的项目(这是由一些外部代码设置的,所以如果我来到设置了这个值的页面,那么我希望选择正确的选项)
  3. 如果我更改下拉列表中的值,请确保更新 otherObj.variable。

最佳答案

angular.module('selects.demo', [])
.controller('SelectCtrl', function($scope){
$scope.values = [{
id: 1,
label: 'aLabel',
}, {
id: 2,
label: 'bLabel',
}];

$scope.selectedval = $scope.values[0];
});
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<div ng-app="selects.demo">
<div ng-controller="SelectCtrl">
<p>Using ngOptions without select as:</p>
<select ng-model="selectedval" ng-options="value.label for value in values"></select>
<p>{{selectedval}}</p>

<p>Using ngOptions with select as statement: (this will return just the id in the model)</p>
<select ng-model="selectedval2" ng-options="value.id as value.label for value in values"></select>
<p>{{selectedval2}}</p>
</div>
</div>

抱歉,如果我的评论有点含糊。 Select像其他表单元素一样的元素实际上是 AngularJS 中的指令,所以它们会自动为你做很多事情。您不需要使用 ngChange 来填充与您的选择元素关联的 ngModel。 AngularJS 会为你处理。

此外,您可以使用 ngOptions而不是 ngRepeat 在选择元素上自动生成选项的值。

假设您有一个具有值的对象:

$scope.values = [{
id: 1,
label: 'aLabel',
}, {
id: 2,
label: 'bLabel',
}];

你会写:

<select ng-model="selectedval" ng-options="value.label for value in values"></select>

现在您的 ngModel 将绑定(bind)到所选元素。它将设置为所选对象的值。如果您将 {{selectedval.id}} 添加到您的 View ,它将显示所选元素的 ID。

如果你想将值设置为第一项,在你的 Controller 中,你将添加:

$scope.selectedval = $scope.values[0]; 

如果你想根据所选值更新 $scope.values 上的某些属性,你可以使用类似的东西:

$scope.addActiveProp = function() {
var selected = $scope.values.filter(function(e) { return e == $scope.selectedval; });
selected.active = true;
}

然后在选择上的 ngChange 中运行 addActiveProp fn。

关于javascript - Angular : Get the index of the dropdown item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31210889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com