角度 ng 选项:按 id 比较

Angular ng-options: compare by id

本文关键字:id 比较 ng 选项 角度      更新时间:2023-09-26

我可以将选择的ng模型设置为对象的键吗?在下面的示例中,默认情况下应选择"item1"。(我不想通过引用比较对象)

<div ng-controller='TestCtrl'>
    <select 
        ng-model='selectedId'
        ng-options='value for (key, value) in items'>
    </select>
</div>
var app = angular.module('myApp', []);
app.controller('TestCtrl', function($scope) {
    $scope.selectedid = 1;
    $scope.items = {
        1: 'item1',
        2: 'item2'
    }   
});

这是jsfiddle:http://jsfiddle.net/h7yb4bys/

结帐 http://jsfiddle.net/oj884ofm/

var app = angular.module('myApp', []);
app.controller('TestCtrl', function($scope) {
    $scope.selectedId = '1';
    $scope.items = {
        1: 'item1',
        2: 'item2'
    }   
});

> 你应该尝试 ' key as value for (key, value) in items ':

<div ng-controller='TestCtrl'>
    <select 
        ng-init="selectedId='1'"
        ng-model='selectedId'
        ng-options='key as value for (key, value) in items'>
    </select>
</div>

你绝对应该考虑使用数组而不是对象。你仍然可以用数组说"items[2]"。这是小提琴和代码。

Javascript:

var app = angular.module('myApp', []);
app.controller('TestCtrl', function ($scope) {
   $scope.items = ['item1', 'item2'];
   $scope.selectedId = $scope.items[0];
});

.HTML:

<div ng-controller='TestCtrl'>
 <select ng-model='selectedId' ng-options='item for item in items'></select>
</div>