質問

For the select tag with angularjs i'm doing:

<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.

役に立ちましたか?

解決

You don't need to write ng-selected, it's not necessary. 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.

<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.

他のヒント

Try to avoid binding to primitives (use objects instead, for instance - $scope.data). So I'd replace levels to data.levels

It's up to you where you really need getdata() call, but controller's initialisation might be a better choice.

Also, if you want to keep your View clean of data, try to declare default value in model (or in service), not in 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

 <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();
               })
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top