2

我正在尝试使用 Angular 的 $http 指令从服务器中提取标签列表,并使用它来填充 select2 选择。我的代码如下所示:

    var samplePage = angular.module('samplePage', ['ui.select2']);

    samplePage.controller('sampleController', function($scope, $http) {
        console.log($scope);
        // THIS WORKS
        $scope.tags = ['a', 'b', 'c'];
        $http.get('angular.html').success(function(rc) {
            console.log($scope);
            // THIS DOES NOT WORK
            $scope.tags = ['d', 'e', 'f'];
        })
    });

    angular.bootstrap(document, ['samplePage']);

但是,“标签”没有更新!或者,更确切地说,“标签”正在更新,但 select2 小部件似乎没有正确绑定。

视图如下所示:

<div ng-app="samplePage">
    <div ng-controller="sampleController">
    <input id="tags" ui-select2="{tags:tags, simple_tags: true}" multiple ng-model="myTags" style="width: 150px;">
    <p>$scope.tags = {{tags}}<p>
    </div>
</div>

这是一个完整的测试应用程序的要点:https ://gist.github.com/poundifdef/6544542

我是否不正确地使用了 select2 模块?还是模块本身有错误?

4

1 回答 1

1

ng-model指令应该是$scope将填充选择输入的指令。改为使用ng-model="tags"

编辑 当你有

<input id="tags" ui-select2="{tags:tags, simple_tags: true}" multiple ng-model="myTags" style="width: 150px;">

tagsinui-select2="{tags:tags, simple_tags: true}"指的是您希望在下拉列表中显示为选项的模型,而inmyTagsng-model="myTags"的是选择的选项。

如果您希望加载列表并选择某些选项,请在控制器中将它们设置为$scope.myTags. 这通常应该是选项的子集(即$scope.tags此处)。

于 2013-09-13T23:36:39.403 回答