0

我有一個工廠,從數據庫中拉下拉選項:在我的控制器選擇由它的價值下拉選項 - Angularjs

app.factory('populateDDL', function($http) { 
    'use strict'; 
    return function (tbl,key) { 
     var json, 
      data = JSON.stringify({ 
       sKey: key, 
       sTableName: tbl 
      }); 
     return $http.post('util.asmx/populateDDL',data). 
     then(function(response) { 
      return JSON.parse(response.data.d); 
     }); 
    }; 
}); 

我然後將這些數據應用到下拉列表/選擇:

app.controller('userSettings', function($scope, $http, populateDDL) { 
      $scope.clinicLocations = new populateDDL('locations',key). 
      then(function(response) { 
       console.log(response); 
       $scope.clinicsDDL = response.locations; 
       $http({ 
        url: 'util.asmx/returnUser', 
        method: 'POST', 
        data: {sUserId: uid}, 
       }) 
       .success(function(user) { 
        $scope.user = user.d; 
       }) 
       .error(function(data, status, headers, config) { 
        console.log(data+', '+status+', '+headers+', '+config); 
       }); 
      }); 
     }); 

這裏是選擇標籤的外觀:

<select ng-model="clinicsDDL.item" ng-options="item.name for item in clinicsDDL track by item.id" ngRequired /> 

下拉列表數據的下降,其投入$ scope.clinicsDDL看起來是這樣的:

[{ 
    "id": "19", 
    "name": "other clinic" 
}, { 
    "id": "39", 
    "name": "My clinic" 
}] 

從數據庫返回的用戶數據是這樣的:

{ 
    "__type": "User", 
    "FirstName": "Erik", 
    "LastName": "Grosskurth", 
    "DefaultLocationId": "39" 
} 

在我的控制我填充下拉列表/選擇,然後我把用戶ID並將其提交給數據庫以獲取用戶信息。此用戶信息返回。從那時起,我想根據從數據庫返回的「DefaultLocationId」從先前填充的列表中選擇一個特定的選項。

我該怎麼做呢?

$scope.clinicsDDL.item = $scope.clinicsDDL[0]; 

^^^不起作用,因爲我不能依賴數組總是形成相同的。我需要基於「DefaultLocationId」而不是一個整數來定位數組項目。在jQuery中,你可以通過使用$('#clinicsDDL option [value =「19」')。doSomething();

我想它會像在角是這樣的:

$scope.clinicsDDL.item = $scope.clinicsDDL[value="19"]; 

^^^但是,這並不工作,要麼

回答

-1

預選擇只使用引用。當你想選擇一個元素並且你不知道哪個字段包含它時,那麼你必須搜索它。除了使用array.filter的(),你應該使用lodash的查找功能(https://lodash.com/docs#find

//preselect DefaultLocationId 39 
$scope.clinicsDDL.item = _.find($scope.clinicsDDL, {DefaultLocationId : 39}); 

_.find(...)將返回不確定時,沒有項目可以發現。所以,你可以把它定義或使用默認值,像

$scope.clinicsDDL.item = _.find($scope.clinicsDDL, {DefaultLocationId : 39}) || $scope.clinicsDDL[0]; 
+0

angular.js:13424的ReferenceError:_沒有定義 –

+0

你必須包括lodash到您的項目和HTML。請參閱[lodash.com](https://lodash.com/)。 –

+0

這不是角度解決方案。我也可以在其他插件中完成一行修復。我正在尋找一個純粹的Angular解決方案,謝謝 –