简体   繁体   English

在 AngularJS onload 的下拉列表中设置选定的选项

[英]Set Selected Option In Dropdown in AngularJS onload

In Angularjs, I have a DropDown:在 Angularjs 中,我有一个下拉列表:

<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. $routeParams.categoryId为“1”,但仍未在下拉列表中设置所选选项。

Your categories variable is an array of objects, while you set the ng-model to an object with only an id.您的categories变量是一个对象数组,而您将ng-model设置为只有一个 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.因为它是一个全新的对象,所以 angular 不会将其视为数组中类别的匹配项,也不会选择正确的对象。

The solution is to set the $scope.category to the matching object of the array instead of creating a new one:解决方案是将$scope.category设置$scope.category的匹配对象,而不是创建一个新对象:

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];
    }
}

You have to change ng-model directive when promise operation is end.promise操作结束时,您必须更改ng-model指令。

<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.假设您有var id = $routeParams.categoryId并且它的值为2例如。 You have to find category from categories where category.id is 2 .您必须从category.id2 categories中找到category For this, the simpliest method is to use a filter method.为此,最简单的方法是使用filter方法。

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

Please take a look to working fiddle请看看工作小提琴

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

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