gpt4 book ai didi

angularjs - ng-repeat 渲染顺序被 ng-if 反转

转载 作者:行者123 更新时间:2023-12-04 08:48:31 25 4
gpt4 key购买 nike

我刚刚遇到这个问题,想知道这是一个错误还是预期的行为?这只是说明问题的一个小例子。以下代码用于两个示例:

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

Plunkr without ng-if

但是第二个例子——它有下面的 item-directive.html——包含一个 ng-if ,这导致列表以相反的顺序呈现?
<div ng-if="item.type == 'test'">

<span>{{::item.title}}</span>

</div>

Plunkr with ng-if

- - - - 更新 - - - - -

我刚刚注意到(这与@squiroid 的回答中提到的问题有关)在此示例中隔离范围实际上不起作用。似乎是,但是 item正在提供给 item-directive ng-repeat 的范围(或者更确切地说是它结束的范围) ,而不是隔离范围。如果您尝试在隔离作用域上设置任何其他值,即使它们显示在传递给指令的链接和 Controller 函数的作用域中(如 plnkr 的控制台输出中所示),它们对模板。除非你删除 replace .

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 会创建一个损坏的作用域

ISSUE

这发生在根元素上的 replace:'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 上没有根元素,从而导致不需要的行为。

关于angularjs - ng-repeat 渲染顺序被 ng-if 反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com