作为 AngularJs 的新手,无法理解这个问题。
这是一个显示操作的简单示例。实际上大约有 50 个项目,在单击元素“String #”后单击“不带字符串”后,以视觉方式删除该项目大约需要 1-2 秒。
我有 Controller 代码:
testApp.controller('TestController', ['$scope', function ($scope) {
$scope.category = [
{id:1, name: "Category 1"},
...
];
$scope.items = [
{id: 1, category: {id: 1},name: "Test 1"},
...
];
$scope.list = [
{id: 1,name: "String 1"}
...
];
angular.forEach($scope.category, function(categoryItem, i) {
categoryHash[categoryItem.id] = i;
});
angular.forEach(menuItems, function(item) {
var catCategory = categoryHash[item.category.id];
if (!$scope.category[catCategory].items) {
$scope.category[catCategory].items = [];
}
$scope.category[catCategory].items.push(item);
});
}])
指令代码:
.directive('listItems', function() {
return {
restrict: 'E',
scope: {
listArray: '=',
listItemId: '=',
listFlag: '='
},
template: '<ul>' +
'<li ng-repeat="listStr in listArray track by listStr.id">' +
'<input type="radio" ' +
'id="list_{{ listItemId }}_{{ listStr.id }}" name="list_{{ listItemId }}" ' +
'ng-model="$parent.$parent.item.string" ng-value="listStr" ng-change="stringSelect()">' +
'<label for="list_{{ listItemId }}_{{ listStr.id }}" ng-bind="listStr.name"></label>' +
'</li>' +
'<li>' +
'<input type="radio" ' +
'id="list_{{ listItemId }}_0" name="list_{{ listItemId }}" ' +
'ng-model="$parent.$parent.item.string" ng-value="" ng-change="stringSelect()">' +
'<label for="list_{{ listItemId }}_0">Without string</label>' +
'</li>' +
'</ul>',
link: function(scope, iElement, iAttrs) {
scope.stringSelect = function() {
scope.listFlag = false;
};
}
}
})
模板:
<div ng-app="test" ng-controller="TestController">
<div ng-repeat="collection in category track by $index" >
<h3 ng-bind="collection.name"></h3>
<ul>
<li ng-repeat="item in collection.items track by $index">
<strong ng-bind="item.name"></strong>
<span ng-if="item.string" ng-bind="item.string.name"></span>
<button ng-click="addString = true" ng-hide="addString">Add String</button>
<div ng-if="addString">
<list-items
list-array="list"
list-item-id="$parent.item.id"
list-flag="$parent.addString"></list-items>
</div>
</li>
</ul>
</div>
</div>
最佳答案
首先删除所有 $parent,它们不是必需的,Angular 会自己在父作用域中查找值,如果您的指令在其他指令中使用,则这甚至不会指向正确的作用域。
第二,使用 Angular,您可以创建很多 watch ,这确实会减慢您的应用程序:
- 当 Angular 监视列表时,他监视进行深度检查。当您有一些包含复杂对象的列表时,这可能会减慢速度。
- 当您使用 {{}} 或 ng-bind 时,它会创建一个监视
3:您使用的是旧版本的 IE 吗?我认为 8 的 Angular 1.2 和范围真的很慢。
因此,您可以尝试不使用默认的数组监视,而是自己处理它,例如仅监视长度。对于 {{}} 部分,从 1.3 开始,您可以在绑定(bind)前面加上 '::' 前缀,以实现一次性绑定(bind) ( https://docs.angularjs.org/#!/guide/expression ),这样他就不会监视更改
4:当您使用 ng-if 时,它会在不需要时销毁对象,并在条件再次为真时重新创建它,也许您应该使用 ng-show 而不是 ng-if
<div ng-if="addString">
关于AngularJs。更改指令中的模型太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35366714/