首页 文章

如何使用带角度的jQuery Select2

提问于
浏览
5

我正在尝试使用带有Angularjs(1.5)的jQuery(2.2.1)Select2(3.5.2),但是很难从选择框中获取数据 . 我已经尝试了ui-select并且我可以检索数据......但是在搜索时经常会崩溃浏览器,速度非常慢且整体不稳定(5000-10000项) . 即使有大量的条目,jQuery Select2也是快速且响应迅速的,但是当我选择一个选项时,我似乎无法获得该对象 .

<head>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/CustomScripts/app.js"></script>
    <script src="~/Scripts/jquery-2.2.1.js"></script>
    <script src="~/Scripts/select2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".sel").select2();
        });
    </script>
<head>
<body ng-app="app" ng-controller="MainCtrl">
    <select class="sel" data-ng-model="country.selected" ng-options="country.Name for country in countries | orderBy: 'Name'">
<body>

app.js

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.country = {};

    $scope.countries = [{
        name: 'Australia',
    }, {
        name: 'United States'
    }, {
        name: 'United Kingdom'
    }];

}]);

有没有办法让这两个很好地工作?

3 回答

  • 0

    可以使用Ang2的Ang2版本 . 点击这里:https://www.npmjs.com/package/angular-select2

    (守则在这里:https://github.com/rubenv/angular-select2

    此Angular库使用Select2作为依赖项,并帮助在表单中集成Select2 .

  • 1

    通过凉亭安装“angular-ui-select”:“= 0.12.1”然后在你的html .....

    <ui-select multiple
                       class="col-md-8 input-sm"
                       on-select="someMethod()"
                       on-remove="someMethod()"
                       ng-model="country.selected"
                       theme="bootstrap">
                <ui-select-match placeholder="Select field...">{{$item.name}}</ui-select-match>
                <ui-select-choices
                        repeat="field in countries | filter:$select.search">
                    <div ng-bind-html="field.name | highlight: $select.search"></div>
                </ui-select-choices>
            </ui-select>
    

    永远不要直接初始化jQuery插件 . 在互联网上搜索如何将jQuery模块与Angular集成(它可能看起来有点复杂,但它很容易 . 以你所做的方式调用它将永远无法工作....

    <script type="text/javascript">
        $(document).ready(function () {
            $(".sel").select2();
        });
    </script>
    

    ui-select的替代方案是:

    angular-chosen ("angular-chosen-localytics": "~1.0.7",)
    

    :)

  • 0

    在搜索了如何从jQuery访问$ scope函数之后,我发现使用angular.element.scope() . function(x)将允许我将每个select2元素的键(在“change”事件中)传递给angular,然后可以操纵 .

    <script type="text/javascript">
        $(document).ready(function () {
            $(".sel").select2({
                placeholder: "Select a project..."
            })
            .on("change", function (e) { angular.element(document.getElementById("MainCtrl")).scope().testfunction(); });
        });
    </script>
    

相关问题