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

Dmi*_*riy 7 javascript angularjs jquery-select2

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

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

这是我的范围代码的一部分:

$scope.select2Options = {
  formatNoMatches: function(term) {
    var message = '<a ng-click="addTag()">???????? ??? "' + term + '"</a>'
    console.log(message); 
    return message;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*ero 6

解决此问题的关键是您必须formatNoMatches在options对象中的函数返回的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;
    }
};
Run Code Online (Sandbox Code Playgroud)

$scope.noResultsTag属性会跟踪返回没有匹配项的用户输入的最后一个值.将更新包装到$scope.noResultsTagwith $.$ 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);
Run Code Online (Sandbox Code Playgroud)

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

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


Sus*_*rut 4

你可以参考这个:

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

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



};
Run Code Online (Sandbox Code Playgroud)

工作小提琴:快速添加新标签