Usman Khalid
Usman Khalid

Reputation: 3110

Set Selected Option In Dropdown in AngularJS onload

In Angularjs, I have a DropDown:

<select ng-model="category" ng-change="categoryChanged(category)" class="form-control" 
data-ng-options="category as category.name for category in categories">
        <option value="">Select Category</option>
</select>

And I have a controller:

app.controller('searchBoxController', ['$scope', '$location', '$routeParams', 'categoryService', function ($scope, $location, $routeParams, categoryService) {
        categoryService.getParentCategory().$promise.then(
        function (model) {
            $scope.categories = model;
            $scope.category.id = $routeParams.categoryId;// Which is coming as "1"
        },
        function (error) {

        });

        $scope.categoryChanged = function (category) {
             alert(category.id);
        };
}]);

$routeParams.categoryId is coming as "1" but still it is not setting the selected option in the dropdown.

Upvotes: 2

Views: 3686

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You have to change ng-model directive when promise operation is end.

<select  ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories">
    <option value="">Select Category</option>
</select>

Suppose you have var id = $routeParams.categoryId and its value is 2 for example. You have to find category from categories where category.id is 2. For this, the simpliest method is to use a filter method.

$scope.category = $scope.categories.filter(function(item){
        return item.id==$scope.id;
})[0];

Please take a look to working fiddle

Upvotes: 0

devqon
devqon

Reputation: 13997

Your categories variable is an array of objects, while you set the ng-model to an object with only an id. Because it is a whole new object, angular doesn't see it as a match of the category in your array, and won't select the correct one.

The solution is to set the $scope.category to the matching object of the array instead of creating a new one:

var id = $routeParams.categoryId;
// Find the category object with the given id and set it as the selected category
for (var i = 0; i < $scope.categories.length; i++){
    if ($scope.categories[i].id == id) {
        $scope.category = $scope.categories[i];
    }
}

Upvotes: 2

Related Questions