Angular-UI select2动态更改选项中的标签属性

hyp*_*erN 1 javascript angularjs jquery-select2 angular-ui

Angular-ui select2标签的官方示例是:

myAppModule.controller('MyController', function($scope) {
    $scope.list_of_string = ['tag1', 'tag2']
    $scope.select2Options = {
        'multiple': true,
        'simple_tags': true,
        'tags': ['tag1', 'tag2', 'tag3', 'tag4']  // Can be empty list.
    };
});
Run Code Online (Sandbox Code Playgroud)

我有这段代码:

$scope.select2Options = {
                        'multiple': true,
                        'simple_tags': true,
                        'tags': $scope.categoryNames
                    };

$scope.$watch(function () { return adminCrudService.getCategoriesForUpdate(); }, function () {
                $scope.action = "edit";
                $scope.categoriesForUpdate = adminCrudService.getCategoriesForUpdate();
                if ($scope.categoriesForUpdate.length > null) {
                    $scope.categoryNames = [];
                    _.forEach($scope.categoriesForUpdate, function (item) {
                        $scope.categoryNames.push(item._backingStore.Name);
                    });

                }
            });
Run Code Online (Sandbox Code Playgroud)

但这只是不起作用,当我点击Selcet2时,我得到没有找到匹配,我在$ watch中记录$ scope.categoryNames,数据就在那里(所以这部分工作正常).

所以我的问题是可以动态加载标签,如果可以,怎么样?

小智 9

我最近在使用AngularUI Select2项目时遇到了这个问题,并通过使tags参数成为返回模型的函数来解决它.例如:

$scope.select2Options = {
  multiple: true,
  simple_tags: true,
  tags: function () {
    return $scope.categoryNames;
  }
};
Run Code Online (Sandbox Code Playgroud)

$scope.categoryNames对视图的任何更新都会反映在视图中,因为Select2会tags在打开时和每次按键时调用该函数.

希望这对想要使用Select2而不是选择的人有用.