角度,选择,设置默认值

时间:2014-01-08 07:36:00

标签: javascript angularjs angular-ui

我知道这可能已被多次询问,但我觉得我正在做的一切正确,但我似乎无法使用AngularJS为选择设置默认选项。

我正在使用: 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变量并填充select选项的事实让我认为$ http.get()已经成功返回,因此$ scope.selectedCompany也应该已经填充。不过我可能错了。

如果有人能看到我出错的地方,并且可以启发我,那就太棒了。

2 个答案:

答案 0 :(得分:1)

$ scope.juice.company是一个从javascript角度来看的对象,它不是包含公司的数组的一部分。您必须自己在公司中找到正确的公司。对于exapmle,假设公司有一个属性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;
}

答案 1 :(得分:0)

您可以在选择中使用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>