AngularJs and <select>: Default selected options are removed

前端 未结 6 1367
梦如初夏
梦如初夏 2021-02-13 16:05

I expect the following code to render a drop down list with the third option selected by default. However, when I bind the select with angularjs, the default selection disappear

6条回答
  •  离开以前
    2021-02-13 16:25

    Angular overrides the "selected" property when you bind the select to a model. If you inspect the rendered DOM you will find that a new item has been added:

    
    

    In order to automatically select the third option you need to pre-populate the model in scope. There are a few ways to do this, including wrapping the select in a controller:

    Selected Colors: {{selectedColors }}

    And then defining that model in the controller.

    var myApp = angular.module('myApp', [])
        .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.selectedColors = 2;
    }]);
    

    Here's a running example.

    http://jsfiddle.net/93926/

    Alternatively, you could just initialize it using ng-init such as in this example:

    http://jsfiddle.net/9JxqA/1/

    EDIT: Removed the selected property in the first example, it's no longer needed.

提交回复
热议问题