2014-01-08 188 views
1

我知道這可能已被多次詢問,但我覺得我一切正常,但我似乎無法爲使用AngularJS的選擇設置默認選項。角度,選擇,設置默認

我使用: AngularJS,角UI路由器,引導

相關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也應該已經被填充。不過,我可能是錯的。

如果有人能看到我要去的地方出錯,並且可以啓發我,那會很棒。

回答

1

$ scope.juice.company是一個從javascript角度看不是包含公司的數組的一部分的對象。你必須親自在公司找到合適的公司。對於exapmle,假設該公司擁有物業編號:

$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; 
} 
+0

這很好用。我猜想具有相同簽名的2個對象不等於同一個對象。 –

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>