AngularJS:ng-options和ng-repeat之间有什么区别

时间:2016-04-18 15:00:48

标签: angularjs

我是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。

第1代码

<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中,但如何指定一些列或字段名称。

2 个答案:

答案 0 :(得分:4)

这两者之间的最大区别可以在ngOptions的文档中找到:https://docs.angularjs.org/api/ng/directive/ngOptions

根据文档,应尽可能使用ngOptions:

  • 通过不为每个重复实例创建新范围来提高内存效益
  • 为选择模型的分配方式提供了更大的灵活性
  • 允许将非字符串值绑定到模型

总而言之,ngOptions指令更灵活,更有效,并且应该避免选项使用ngRepeat

答案 1 :(得分:1)

ng-optionsng-repeat的专用变体。

ng-options专门用<select>填充<options>列表。

ng-repeat更常用,就像您在Javascript中使用forEach或在Python中使用for user in userlist一样。

相关问题