在Angularjs,我有一个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>
我有一个控制器:
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”,但仍未在下拉列表中设置所选选项。
答案 0 :(得分:1)
您的categories
变量是一个对象数组,而您将ng-model
设置为只有id的对象。因为它是一个全新的对象,angular不会将其视为数组中类别的匹配,也不会选择正确的对象。
解决方法是将$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];
}
}
答案 1 :(得分: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
。您必须在category
categories
category.id
2
中找到filter
。为此,最简单的方法是使用$scope.category = $scope.categories.filter(function(item){
return item.id==$scope.id;
})[0];
方法。
public static boolean allNotNull(Object... objects) {
for (Object o : objects) {
if (o == null) {
return false;
}
}
return true;
}
if(allNotNull(objectA, objectB, objectC))