angularjs – ng-repeat渲染顺序由ng-if反转
栏目: JavaScript · 发布时间: 6年前
内容简介:翻译自:https://stackoverflow.com/questions/28648762/ng-repeat-render-order-reversed-by-ng-if
我刚刚遇到这个,我想知道这是一个错误还是预期的行为?这只是一个显示问题的小例子.以下代码用于两个示例:
<body ng-app="app" ng-controller="AppCtrl">
<item-directive ng-repeat="item in ::items" item="item"></item-directive>
</body>
angular
.module('app', [])
.controller('AppCtrl', AppCtrl)
.directive('itemDirective', itemDirective)
.factory('model', model);
function AppCtrl($scope, model) {
$scope.items = model.getItems();
}
function itemDirective() {
return {
restrict: 'E',
replace: true,
scope: {
item: '='
},
templateUrl: 'item-directive.html'
};
}
function model() {
return {
getItems: getItems
}
function getItems() {
return [
{
type: 'test',
title: 'test 1'
},
{
type: 'test',
title: 'test 2'
},
{
type: 'test',
title: 'test 3'
}
];
}
}
第一个示例有这个item-directive.html,它按预期以正确的顺序呈现
<div>
<span>{{::item.title}}</span>
</div>
但是第二个例子 – 它有以下item-directive.html – 包含一个ng-if,它导致列表以相反的顺序呈现?
<div ng-if="item.type == 'test'">
<span>{{::item.title}}</span>
</div>
——–更新———-
我刚刚注意到(这与@ squiroid的回答中提到的问题有关)隔离范围在这个例子中实际上并不起作用.它似乎是,但是项目指令范围(或者更确切地说它最终的范围)可以通过ng-repeat,而不是隔离范围.如果您尝试在隔离范围上设置任何其他值,即使它们显示在传递给指令的链接和控制器函数的范围上(如plnkr的控制台输出中所示),它们也不可用于模板.除非你删除替换.
Plunkr showing broken isolate scope
Plunkr showing fixed isolate scope when replace:false
—更新2 —
我已经更新了两个示例,以显示一旦删除隔离范围后问题仍然存在
Plunkr without ng-if and no isolate scope
Plunkr with ng-if and no isolate scope
还有一个新版本显示了从templateUrl到模板的更改 – 正如@Manube所建议的那样 – 显示了按预期工作的行为
Plunkr with ng-if and no isolate scope using template instead of templateUrl
在带有replace:true的指令的根元素上使用ng-if会创建一个损坏的范围
这种情况发生在替换:’true’和ng-if在根元素上的组合.
确保templateUrl中html的内容只有一个根元素.
如果你把ng-if放在span上
<div >
<span ng-if="item.type == 'test'">{{::item.title}}</span>
</div>
现在为什么会发生这种情况,因为ngIf指令基于{expression}删除或重新创建DOM树的一部分.如果分配给ngIf的表达式求值为false值,则从DOM中删除该元素,否则将元素的克隆重新插入DOM.
这可能导致在渲染时templateUrl上没有根元素,从而导致不必要的行为.
翻译自:https://stackoverflow.com/questions/28648762/ng-repeat-render-order-reversed-by-ng-if
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Go数组反转练习
- LeetCode (206):反转链表
- LeetCode (206):反转链表
- leetcode 206 反转链表
- OpenCV图像颜色反转示例
- leetcode刷题-----7. 整数反转
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数学建模算法与应用
司守奎、孙玺菁 / 国防工业出版社 / 2011-8 / 49.00元
《数学建模算法与应用》主要内容简介:作者司守奎、孙玺菁根据多年数学建模竞赛辅导工作的经验编写《数学建模算法与应用》,涵盖了很多同类型书籍较少涉及的新算法和热点技术,主要内容包括时间序列、支持向量机、偏最小二乘面归分析、现代优化算法、数字图像处理、综合评价与决策方法、预测方法以及数学建模经典算法等内容。《数学建模算法与应用》系统全面,各章节相对独立。《数学建模算法与应用》所选案例具有代表性,注重从不......一起来看看 《数学建模算法与应用》 这本书的介绍吧!