Use select2 plugin in AngularJS application
Asked Answered
G

2

7

I use select2 plugin in my AngularJS application for displaying list of some entities (tags). This is my template's part:

select.ddlTags(ui-select2="select2Options", multiple, ng-model="link.tags")
      option(ng-repeat="tag in tags", value="{{tag.id}}") {{tag.name}}

and this is my scope code's part:

$scope.select2Options = {
  formatNoMatches: function(term) {
    var message = '<a ng-click="addTag()">Добавить тэг "' + term + '"</a>'
    console.log(message); 
    return message;
  }
}

I want to provide ability to quickly add a new tag if it isn't exist in the tags list. So I override formatNoMatches select2 option to display 'add new tag' link. How I should properly bind addTag() function from $scope to the click event of the link?

Gyniatrics answered 10/7, 2013 at 13:41 Comment(2)
can you add it in a scope .. ie. $scope.addTag = function() { }Acrimony
I have been fighting with the same issues for many days now. I get the feeling that angular needs to be told about the <a> tag that we are making. But I cannot figure out how.Thread
P
6

The key to the solution of this problem is that you have to use the $compile service on the HTML returned by the formatNoMatches function in the options object. This compilation step will wire up the ng-click directive in the markup to the scope. Unfortunately, that is a bit easier said than done.

You can see the full working example here: http://jsfiddle.net/jLD42/4/

There is no way that I know of for AngularJS to watch the select2 control to monitor the results of a search, so we must inform the controller when no results are found. This is easy to do through the formatNoMatches function:

$scope.select2Options = {
    formatNoMatches: function(term) {
        console.log("Term: " + term);
        var message = '<a ng-click="addTag()">Add tag:"' + term + '"</a>';
        if(!$scope.$$phase) {
            $scope.$apply(function() {
                $scope.noResultsTag = term;
            });
        }
        return message;
    }
};

The $scope.noResultsTag property keeps track of the last value entered by the user that returned no matches. Wrapping the update to the $scope.noResultsTag with $scope.$apply is necessary because formatNoMatches is called outside the context of the AngularJS digest loop.

We can watch $scope.noResultsTag and compile the formatNoMatches markup when changes occur:

$scope.$watch('noResultsTag', function(newVal, oldVal) {
    if(newVal && newVal !== oldVal) {
        $timeout(function() {
            var noResultsLink = $('.select2-no-results');
            console.log(noResultsLink.contents());
            $compile(noResultsLink.contents())($scope);
        });
    }
}, true);

You may wonder what the $timeout is doing there. It is used to avoid the race condition between the select2 control updating the DOM with the formatNoMatches markup and the watch function trying to compile that markup. Otherwise, there is a good chance that the $('.select2-no-results') selector will not find what it is looking for and the compilation step won't have anything to compile.

Once the add tag link has been compiled, the ng-click directive will be able to call the addTag function on the controller. You can see this in action in the jsFiddle. Clicking the add tag link will update the Tags array with the search term you enter into the select2 control and you will be able to see it in the markup and the options list the next time you enter a new search term into the select2 control.

Pinnati answered 5/9, 2013 at 7:24 Comment(1)
Seems to work well. I've been struggling with this problem. Thanks!Cardiganshire
W
4

You can refer this :

HTML

<div ng-controller="MyCtrl">
       <input ng-change="showDialog(tagsSelections)" type="text" ui-select2="tagAllOptions" ng-model="tagsSelections" style="width:300px;" /> 
       <pre> tagsSelection: {{tagsSelections | json}}</pre>        
</div>

JS

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

function MyCtrl($scope, $timeout) {

    // Initialize with Objects.
    $scope.tagsSelection = [{
        "id": "01",
            "text": "Perl"
    }, {
        "id": "03",
            "text": "JavaScript"
    }];

    $scope.showDialog = function (item) {
        console.log(item); // if you want you can put your some logic.
    };

    $timeout(function () {
        $scope.tagsSelection.push({
            'id': '02',
                'text': 'Java'
        });
    }, 3000);

    $scope.tagData = [{
        "id": "01",
            "text": "Perl"
    }, {
        "id": "02",
            "text": "Java"
    }, {
        "id": "03",
            "text": "JavaScript"
    }, {
        "id": "04",
            "text": "Scala"
    }];

   // to show some add item in good format
    $scope.formatResult = function (data) {
        var markup;
        if (data.n === "new") markup = "<div> <button class='btn-success btn-margin'><i class='icon-plus icon-white'></i> Create :" + data.text + "</button></div>";
        else markup = "<div>" + data.text + "</div>";
        return markup;

    };

    $scope.formatSelection = function (data) {
        return "<b>" + data.text + "</b></div>";
    };

    $scope.tagAllOptions = {
        multiple: true,
        data: $scope.tagData,
        tokenSeparators: [","],
        createSearchChoice: function (term, data) { // this will create extra tags.
            if ($(data).filter(function () {
                return this.v.localeCompare(term) === 0;
            }).length === 0) {
                return {
                    id: term,
                    text: term,
                    n: "new",
                    s: ""
                };
            }
        },
       // initSelection: function(element, callback) { //if you want to set existing tags into select2
   //   callback($(element).data('$ngModelController').$modelValue);
   //  },
        formatResult: $scope.formatResult,
        formatSelection: $scope.formatSelection,
        dropdownCssClass: "bigdrop",
        escapeMarkup: function (m) {
            return m;
        }
    };



};

Working Fiddle : Quickly add a new tag

Whity answered 2/9, 2013 at 7:42 Comment(3)
Working Fiddle not working in Chrome 29. Uncaught Error: No module: ui.select2Asymmetric
The Problem with the solution(which in-fact is the original problem) is that the "Create" button is still out of Angular's digest cycle and the newly added item remains unknown to angular.Thread
The Fiddle doesn't work because the reference to the select2 library is broken. It's a raw GitHub reference with a MIME type of text/plain which is not allowed by jsFiddle.Pinnati

© 2022 - 2024 — McMap. All rights reserved.