从下拉列表中选择一个选项 - Angularjs

时间:2016-07-06 14:42:08

标签: angularjs drop-down-menu html-select angular-ngmodel angularjs-ng-options

我有一个工厂从数据库中提取下拉选项:

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标记的外观:

<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并将其提交给数据库以获取用户信息。该用户信息返回。从那时起,我想根据从DB返回的“DefaultLocationId”从先前填充的列表中选择一个特定选项。

我该怎么做呢?

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

^^^不起作用,因为我不能依赖于数组总是形成相同的。我需要根据“DefaultLocationId”而不是整数来定位数组项。

在jQuery中,您将使用$('#clinicsDDL选项[value =“19”')来定位选择器.doSomething();

我当时认为这就像是像这样的角色:

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

^^^但不起作用

1 个答案:

答案 0 :(得分:-1)

预选仅使用参考。当您想要选择一个元素并且您不知道哪个字段包含它时,您必须搜索它。不要使用array.filter(),而应使用lodash的find函数(https://lodash.com/docs#find

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

_。当没有找到任何项目时,find(...)将返回undefined。所以你可以保持未定义或使用默认值,如

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