我使用select2 angular来自动完成标记,它工作得很好,但如果我加载超过4000条记录,它会停止执行并阻塞网页。
有办法解决这个问题吗?
我的代码HTML<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.0/select2.min.js"></script>
<script src="https://rawgithub.com/angular-ui/ui-select2/master/src/select2.js"></script>
<div ng-controller="MyCtrl">
No Results Tag: {{ noResultsTag }}
<br />
<select style="width: 400px;" ui-select2="select2Options" multiple ng-model="selectedTags">
<option ng-repeat="tag in tags" value="{{tag.id}}">{{tag.name}}</option>
</select>
<br /><br />
Tags:
<pre>
{{ tags | json }}
</pre>
</div>
Javascript var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope, $compile, $timeout) {
$scope.noResultsTag = null;
$scope.tags = [
{id: 0, name: "Zero"},
{id: 1, name: "One"},
{id: 2, name: "Two"},
{id: 3, name: "Three"},
{id: 4, name: "Four"},
];
$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.addTag = function() {
$scope.tags.push({
id: $scope.tags.length,
name: $scope.noResultsTag
});
};
$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);
}
这个例子运行良好的问题是成千上万的记录。测试http://jsfiddle.net/jld42/4/
我之前也遇到过同样的问题。在我们的例子中,解决方案是使用AJAX调用加载数据并对结果进行分页。这确保了插件不会冻结整个页面,并且数据可以以很好的速度加载。
请看这里的官方文档:https://select2.github.io/examples.html#data-ajax