在AngularJS应用程序中使用select2插件

Use select2 plugin in AngularJS application

本文关键字:select2 插件 AngularJS 应用程序      更新时间:2023-09-26

我在AngularJS应用程序中使用select2插件来显示一些实体(标记)的列表。这是我模板的一部分:

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

这是我的范围代码部分:

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

如果标签列表中不存在新标签,我想提供快速添加新标签的功能。所以我覆盖formatNoMatches select2选项来显示"添加新标签"链接。如何将addTag()函数从$scope正确绑定到链接的点击事件?

解决此问题的关键是必须对options对象中formatNoMatches函数返回的HTML使用$compile服务。此编译步骤将把标记中的ng-click指令连接到作用域。不幸的是,这说起来容易做起来难。

您可以在此处查看完整的工作示例:http://jsfiddle.net/jLD42/4/

据我所知,AngularJS无法观看select2控件来监控搜索结果,因此当没有找到结果时,我们必须通知控制器。这很容易通过formatNoMatches功能实现:

$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;
    }
};

$scope.noResultsTag属性跟踪用户输入的最后一个未返回匹配项的值。用$scope包装对$scope.noResultsTag的更新$apply是必要的,因为formatNoMatches是在AngularJS摘要循环的上下文之外调用的。

我们可以观看$scope.noResultsTag,并在发生更改时编译formatNoMatches标记:

$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);

您可能想知道$timeout在那里做什么。它用于避免select2控件用formatNoMatches标记更新DOM和watch函数试图编译该标记之间的竞争条件。否则,$('.select2-no-results')选择器很可能找不到它要查找的内容,并且编译步骤将没有任何要编译的内容。

一旦编译了添加标签链接,ng-click指令将能够调用控制器上的addTag函数。您可以在jsFiddle中看到这一点。单击添加标记链接将使用您在select2控件中输入的搜索词更新标记数组,下次在select2中控件中输入新的搜索词时,您将能够在标记和选项列表中看到它。

您可以参考以下内容:

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

};

工作Fiddle:快速添加新标签