2017-01-18 26 views
1

在Angularjs,我有一個下拉:組選定的選項在下拉在AngularJS的onload

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

而且我有一個控制器:

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即將爲 「1」,但它仍然是不在下拉菜單中設置選定的選項。

+1

的可能的複製[我如何設置angularjs選擇框的默認值(http://stackoverflow.com/questions/18380951/how-do-i -set-default-value-of-select-box-in-angularjs) – xkcd149

+0

你必須在控制器的開頭聲明'$ scope.category = {};'。 – Mistalis

+0

@ xkcd149對不起,但我的問題不重複。我只有$ routeParams中的id,而標記爲重複的問題則集中在整個對象上。 –

回答

0

你必須改變ng-model指令時promise操作結束。

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

假設你有var id = $routeParams.categoryId和它的價值是2例如。您必須從categories找到category,其中category.id2。爲此,最簡單的方法是使用filter方法。

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

請看看到working fiddle

+1

我不是downvoter,但我可以看到你給出的解決方案不解決OP的問題。您只需將'category'設置爲數組的第一項,而不是使用'$ routeParams'的給定ID – devqon

1

您的categories變量是一個對象數組,當您將ng-model設置爲只有一個id的對象時。因爲它是一個全新的對象,所以角度不會將其視爲數組中類別的匹配,並且不會選擇正確的對象。

的解決方案是將$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]; 
    } 
} 
相關問題