gpt4 book ai didi

AngularJS : ng-if | Hidden(Removed) ng-model variable not removed from $scope

转载 作者:行者123 更新时间:2023-12-01 09:25:57 25 4
gpt4 key购买 nike

我试图理解 ng-if 与 ng-show 的对比。阅读文档并完成相关的 stackoverflow 问题后 here ,我知道 ng-if 删除了 DOM 元素,并且删除了 ng-if 中的范围变量。即“已删除”ng-if 元素中的 ng-model 变量不会出现在 $scope 中。

来自 Angular ng-if docs :-

Note that when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance. An important implication of this is if ngModel is used within ngIf to bind to a javascript primitive defined in the parent scope.

考虑以下代码片段:-

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script>
</head>
<body data-ng-app="myModule">
<div data-ng-controller="TestController">
<input name="first" type="number" data-ng-model="form.x" placeholder="Enter Number X"/>
<input name="second" type="number" data-ng-if="form.x>5" data-ng-model="form.y" placeholder="Enter Number Y"/>
<input type="button" value="Click" ng-click="save()"/>
</div>
<script type="text/javascript">
var myModule = angular.module("myModule",[]);
myModule.controller("TestController",function($scope){
$scope.form = {};
$scope.form.x = 0;
$scope.form.y = 0;
$scope.save = function(){
console.log($scope.form);
};
});
</script>
</html>

这是一个非常简单的用例 - 仅当第一个大于 5 时才显示第二个数字输入字段。

保存按钮单击代表 Controller 中的“保存”功能,该功能仅打印出 $scope 的“表单”对象。

问题:-

输入 1:-输入 x=6 和 y=2输出 1:{x: 6, y: 2}

输入 2:-输入 x=3输出 2:{x: 3, y: 2}

我无法理解为什么“输出 2”仍显示 y =2。如果它的 DOM 已被删除,输出不应该只是 {x:3} 吗?

如果我想从作用域中移除(ngIf-removed)模型该怎么办?

谢谢

最佳答案

问题

为了进一步说明@Chandermani 在评论中指出的内容,ng-if 创建了一个 new 范围,它有自己的变量。但是,它在原型(prototype)上确实继承自其父范围,因此如果您在现有父对象上设置属性,例如您正在使用 form.y 执行的操作,则当子范围被销毁时,该属性不受影响。

快速修复解决方案

您可以将另一个指令添加到与您设置 ng-if 的元素相同的元素,该指令 delete 范围内的属性$destroy:

指令

myModule.directive('destroyY', function(){
return function(scope, elem, attrs) {
scope.$on('$destroy', function(){
if(scope.form.y) delete scope.form.y;
})
}
});

查看

<input ... data-ng-if="form.x>5" destroy-y .../>

Demo

注意:我看到@user2334204 发布了类似的内容。我还是决定发布这个,因为这里不必在每个摘要中检查 x 的值

关于AngularJS : ng-if | Hidden(Removed) ng-model variable not removed from $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042811/

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