Alliswell
Alliswell

Reputation: 1583

Preselected option by ng-init doesn't work in ngOptions | AngularJS

I have object product = {id: "759", name: "someName", category_id: "139", cartridge_type: 2 ...} in my angular controller.

Why preselected option in ngOptions doesn't work? Select renders empty option as if product.cartridge_type would be null.

HTML

<select class="form-control"
        id="cartridge_type"
        name="cartridge_type"

        ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0]"
        ng-model="product.cartridge_type"
        ng-options="cartridge_type.id as cartridge_type.name for cartridge_type in cartridgeTypeScope">

    <option value="">Select type</option>
</select>

JS

$http.get('someApiPath').success(function(data) {
    $scope.product = data[0];
    console.log( $scope.product );
});

$scope.cartridgeTypeScope = [
    {
        id: 0,
        name  : '-'
    },
    {
        id: 1,
        name  : 'cartridgeType1'
    },
    {
        id: 2,
        name  : 'cartridgeType2'
    }
]

Upvotes: 2

Views: 1306

Answers (1)

squiroid
squiroid

Reputation: 14027

Just simple use cartridgeTypeScope[0].id in ng-init

ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0].id"

Thing is that you are using cartridge_type.id as cartridge_type.name which is expecting id in the select but in ng-init you are providing it complete object (cartridgeTypeScope[0]). So it is not selecting your option value.

Alternatively you can do You can use same ng-init but remove cartridge_type.id as from your ng-options

ng-init="product.cartridge_type=product.cartridge_type||cartridgeTypeScope[0]"

 ng-options="cartridge_type.name for cartridge_type in cartridgeTypeScope"

Hope It help :)

UPDATE

For controller default option you need to do

  $scope.product={
    "cartridge_type":2
  }

UPADTE 2:- For $http:-

Plunker

Upvotes: 3

Related Questions