数组未使用 AngularJs 绑定到 select

array not binding to select using AngularJs

我正在像这样填充一个名为 CommandGroup 的集合

        function getCommandGroups() {
        $scope.commandGroups = commandGroupResource.query();

        return $scope.commandGroups.$promise.then(function (response) {

            $scope.commandGroups = response;

        });

    }

我的 html 看起来像这样。

                        <select ng-model="vm.Job.CommandGroup" name="ddlCommandGroup" bootstrap-dropdown>
                        <option value="">Select Something</option>
                        <option ng-repeat="cmdGroup in commandGroups" value="{{cmdGroup.Id}}">{{cmdGroup.Name}}</option>
                    </select>

由于某种原因,下拉列表仍然是空的。函数 getCommandGroups() 调用后端并使用对象数组填充 commandGroups,每个对象都有 Id 和 Name。

请帮忙。

更新

我发现指令 bootstrap-dropdown 有问题,因为它是 Bootstrap-select

angular
.module('app').directive('bootstrapDropdown', ['$timeout',
    function ($timeout) {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModel) {                  
                $timeout(function () {
                    element.selectpicker();
                });
            }
        };
    }
]);

This plunk 包含您提供的确切代码,但 bootstrap-dropdown 指令和您的实际 Web 服务除外。代码按预期运行。这表明您未提供的代码中的其他地方存在问题。

可能的问题:

  1. bootstrap-dropdown 指令正在做一些有趣的事情。

    一个。 更新:该指令在 this plunk 中有效 "fine"。不确定它应该做什么,但它不会导致您描述的行为。

  2. 您的标记中缺少 ng-controller

  3. 我们看不到的其他东西正在清除 $scope.commandGroups.

重新分配 $scope.commandGroups 可能会干扰承诺解析/范围摘要周期。尝试将函数更改为以下内容:

function getCommandGroups() {
    commandGroupResource.query().$promise.then(function (response) {
        $scope.commandGroups = response;
    });
}

我认为问题在于第三方 JavaScript (bootstrap-select) 没有收到有关更改的通知。 在将响应分配给 commandGroups 后,您可能必须在元素上调用 selectpicker('refresh')

更新: 在调用 selectpicker('refresh'):

之前还需要使用 $scope.$apply()
function getCommandGroups() {
    $scope.commandGroups = commandGroupResource.query();

    return $scope.commandGroups.$promise.then(function (response) {
        $scope.commandGroups = response;
        $scope.$apply();
        $('.mySelect').selectpicker('refresh'); 
    });
}

请参阅下面的评论,了解 Taylor Buchanan 的 Plunk 的分支,以了解实际效果。

更新 2:使用超时来防止 "digest already in progress" 错误:

function getCommandGroups() {
   $scope.commandGroups = commandGroupResource.query();

   return $scope.commandGroups.$promise.then(function (response) {
        $scope.commandGroups = response;
        $timeout(
           function(){
               $('.mySelect').selectpicker('refresh'); 
           }
        );
   });
}