2

I'm attempting to use Angular's $http directive to pull a list of tags from a server, and use that to populate a select2 select. My code looks like this:

    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']);

However, the "tags" is not being updated! Or, rather, "tags" is being updated but the select2 widget does not seem to be binding properly.

The view looks like this:

<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>

Here's a gist with a full test application: https://gist.github.com/poundifdef/6544542

Am I using the select2 module improperly? Or is there a bug in the module itself?

1 Answer 1

1

The ng-model directive should be the $scope that will populate the select input. Use ng-model="tags"instead.

EDIT When you have

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

The tagsin ui-select2="{tags:tags, simple_tags: true}"refers to the model you want to appear as options in the dropdown while myTags in ng-model="myTags" refers to the options that are selected.

If you want the list to be loaded with some options selected, set them in the controller as $scope.myTags. This should normally be a sub-set of the options (that is, $scope.tags here).

Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful! But not quite: when I change the code to say ng-model="tags", the dropdown's options are still ['a', 'b', 'c']. Theoretically, that list should no longer exist anywhere, if binding was done properly. Similarly, ['d', 'e', 'f'] never appear as options (even if I de-select them.)
@poundifdef you are performing a get request on the current page. Replace it with the source you want to load from and it will go away i.e. the a,b,c.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.