[英]Angular, Select, Set Default
我知道這個問題可能已經被問過多次了,但是我覺得我所做的一切都很好,但是我似乎無法使用AngularJS為select設置默認選項。
我正在使用 :AngularJS,Angular-UI-router,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;
});
在我的控制器中 :
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也應該已經填充。 我可能是錯的。
如果有人可以看到我要去哪里出了問題並可以啟發我,那真是太棒了。
從javascript的角度來看,$ scope.juice.company是一個對象,它不是包含公司的數組的一部分。 您必須自己在公司中找到正確的伙伴。 例如,假設公司具有財產編號:
$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;
}
您可以在選擇中將id用作模型,然后在控制器中進行設置:
app.controller('Ctrl', function ($scope) {
var opentr;
$scope.juices = [];
$scope.juice = 2;
$scope.juices.push({"id": 1 , "fruit": "orange"});
$scope.juices.push({"id": 2 , "fruit": "apple"});
$scope.juices.push({"id": 3 , "fruit": "pear"});
$scope.juices.push({"id": 4 , "fruit": "pinapple"});
});
HTML:
{{ juice }}
<select ng-model="juice" ng-options="juice.id as juice.fruit for juice in juices"></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.