javascript - 数组未绑定(bind)到使用 AngularJs 选择

标签 javascript angularjs select angular-promise

我正在像这样填充一个名为 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。

请帮忙。

enter image description here

更新

我发现指令 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();
                });
            }
        };
    }
]);

最佳答案

我认为问题在于第三方 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:使用超时来防止“摘要已在进行中”错误:

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

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

关于javascript - 数组未绑定(bind)到使用 AngularJs 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147790/

相关文章:

MySQL 选择具有公共(public)列的行

mysql - 错误代码 : 1054. 'sdate' 中的未知列 'where clause'

javascript - 为什么我的嵌套 For 循环在使用 Vue 时只返回第二个数组的第一个值?

javascript - 如何使 Vue 组件与 v-model 保留值类型一起工作?

javascript - AngularJS - 显示项目层次结构,每个分组在其自己的容器中

angularjs - ng-repeat 中的单独进度条

javascript - 如何处理 tree shaking 代码中的副作用?

javascript - `AudioContext().audioWorklet.addModule()`,如何通过 `Blob` 加载?

javascript - Angular 1.5 使用 transclude 或不使用 transclude

javascript - 如何按键对ng-options中的数组进行排序?