我知道这可能已经被问过多次,但我觉得我做的一切都是正确的,但我似乎无法使用 AngularJS 设置默认选项。
我正在使用: AngularJS、Angular-UI 路由器、Bootstrap
相关 HTML:
<select ng-model="selectedCompany" ng-options="c.name for c in companies" class="form-control"></select>
果汁服务:
vapelog.factory('Juices', function($http, $q){
var Juices = {
get : function() {
var promise = $http.get('/juices').then(function(data){
return data.data;
});
return promise;
},
show : function(id) {
var deferred = $q.defer();
$http.get('/juices/'+id).then( function ( juice ) {
$http.get('/companies').then( function ( companies ) {
juice.companies = companies;
deferred.resolve( juice );
}, function getAcctError() { deferred.reject(); } );
}, function getUserError() { deferred.reject(); } );
return deferred.promise;
},
}
return Juices;
});
在我的 Controller 中:
vapelog.controller('JuiceDetailCtrl', ['$scope','$stateParams','Juices',function($scope, $stateParams, Juices) {
var id = $stateParams.juice;
$scope.juice = {};
$scope.selectedCompany = {};
Juices.show(id).then(function(juice){
$scope.juice = juice.data;
$scope.companies = juice.companies.data;
$scope.reviews = $scope.juice.reviews;
$scope.selectedCompany = $scope.juice.company;
}, function(){
console.log('error');
});
$scope.tfIcon = function(item){
if(item == "1"){
return 'glyphicon-ok';
} else {
return 'glyphicon-remove';
}
}
}]);
所有内容都会预先填充,选择框包含所有项目,但不会预先选择该项目。它以空白选择选项开始。
设置 $scope.companies 变量并填充选择选项的事实让我认为 $http.get() 已经成功返回,因此 $scope.selectedCompany 也应该已经填充。不过我可能是错的。
如果有人能看到我哪里出了问题,并能启发我,那就太棒了。
最佳答案
$scope.juice.company 是一个对象,从 JavaScript 的 Angular 来看,它不是包含公司的数组的一部分。你必须自己在公司中找到正确的公司。例如,假设公司有一个属性 ID:
$scope.selectedCompany = findCompany($scope.juice.company, $scope.companies);
function findCompany(theCompany, companies){
var result;
angular.forEach(companies, function(companieInArray){
if(companieInArray.id === theCompany.id){
result = companieInArray;
}
});
return result;
}
关于javascript - Angular 、选择、设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20989583/