简体   繁体   English

Angularjs:正确选择ng-options

[英]Angularjs: Select ng-options right way

For the select tag with angularjs i'm doing: 对于带有angularjs的select标签,我正在做:

<select ng-init="getdata()" data-ng-model="ob.id" 
        data-ng-options="level.id as level.desc for level in levels" 
        data-ng-selected="ob.id == level.id"> 
        <option value="0">default...</option>
</select>

... but is this the right way because there are so many other ways on the web? ...但这是正确的方式,因为网上还有很多其他方式吗? getdata() gets $scope.levels array. getdata()获取$ scope.levels数组。

Try to avoid binding to primitives (use objects instead, for instance - $scope.data). 尽量避免绑定到基元(例如使用对象,例如 - $ scope.data)。 So I'd replace levels to data.levels 所以我代替levelsdata.levels

It's up to you where you really need getdata() call, but controller's initialisation might be a better choice. 这取决于你真正需要getdata()调用的地方,但控制器的初始化可能是更好的选择。

Also, if you want to keep your View clean of data, try to declare default value in model (or in service), not in View. 此外,如果要保持View清理数据,请尝试在模型(或服务中)中声明默认值,而不是在View中。

Your way is one of the good way. 你的方式是一个好方法。

I have another way with some custom coding . 我有一些自定义编码方式。

Here is a code for my sample. 这是我的示例代码。

Html code Html代码

 <div class="col-sm-6 form-group">
            <label for="companyName">Tenants</label>
            <select class="form-control input-lg" ng-model="selectedTenant" 
             required ng-options="i.CompanyName for i in tenants">
            </select>
        </div>

Angular Code 角度代码

$http.get('/tenants')
               .success(function (response) {
                   response.push({ CompanyName: "Select", TenantId: 0 });
                   $scope.tenants = response;
                   $scope.selectedTenant = response[$scope.tenants.length - 1];
                   $scope.$apply();
               })

You don't need to write ng-selected, it's not necessary. 您不需要编写ng-selected,也没有必要。 Also ng-init should just be used in really specific cases ( nginit ) so as OZ mentioned it'd better to call getData() from the controller. 另外ng-init应该只用于特定的情况( nginit ),因为OZ提到最好从控制器调用getData()。

<select data-ng-model="ob.id" 
        data-ng-options="level.id as level.desc for level in levels"> 
    <option value="0">default...</option>
</select>

Other than that the select looks correct. 除此之外,选择看起来正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM