Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use select2 plugin in AngularJS application

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?

like image 572
Dmitriy Avatar asked Jul 10 '13 13:07

Dmitriy


2 Answers

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.

like image 86
Justin Lovero Avatar answered Sep 21 '22 03:09

Justin Lovero


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

like image 25
Sushrut Avatar answered Sep 23 '22 03:09

Sushrut