我是angular.i中的新人,看到人们使用ng-options and ng-repeat
来填充下拉。我也看到人们使用ul/li
生成表格数据或生成ng-repeat
相关数据。
我想知道 ng-options和ng-repeat之间有什么区别?
这里我将设置代码并填充下拉列表。在第一种情况下使用 ng-option ,在第二种情况下使用 ng-repeat 。因此我是棱角分明的新人,所以不明白 ng-options和ng-repeat之间的区别?
还告诉我在什么样的情况下人们可以使用ng-options而不是使用ng-repeat。
<div ng-app="main" ng-controller="DemoCtrl">
<select ng-options="r.countryId as r.name for r in chooseCountries" ng-model="selectedCountry">
</select>
</div>
var app = angular.module('main', []);
app.controller('DemoCtrl', function ($scope) {
$scope.chooseCountries = [
{ countryId: 0, name: "Select Account", desc: "some description" },
{ countryId: 1, name: "France - Mainland", desc: "some description" },
{ countryId: 2, name: "Gibraltar", desc: "some description" },
{ countryId: 3, name: "Malta", desc: "some description" }
];
$scope.selectedCountry = $scope.chooseCountries[2].countryId;
});
<div ng-controller="DemoCtrl" ng-app="main">
<select ng-model="selectedCountry">
<option value="">Select Account</option>
<option ng-repeat="x in chooseCountries" ng-value="x.countryId" >{{x.name}}</option>
</select>
</div>
var app = angular.module('main', []);
app.controller('DemoCtrl', function ($scope) {
$scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 2, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
$scope.selectedCountry = $scope.chooseCountries[1].name;
});
请告诉我在哪里可以使用 ng-option 以及我们不能使用的地方。还告诉我哪里 ng-repeat 仅适用。
另一个问题是,如何在使用ng-repeat时指定列名.....是否可能?
如果我的对象有很多字段,那么请参阅此代码ng-repeat="x in chooseCountries"
,然后将所有字段都加载到x中,但如何指定一些列或字段名称。
答案 0 :(得分:4)
这两者之间的最大区别可以在ngOptions的文档中找到:https://docs.angularjs.org/api/ng/directive/ngOptions
根据文档,应尽可能使用ngOptions:
总而言之,ngOptions指令更灵活,更有效,并且应该避免选项使用ngRepeat
答案 1 :(得分:1)
ng-options
是ng-repeat
的专用变体。
ng-options
专门用<select>
填充<options>
列表。
ng-repeat
更常用,就像您在Javascript中使用forEach
或在Python中使用for user in userlist
一样。