gpt4 book ai didi

javascript - Angular 中的范围变量和 ng-include 不协调

转载 作者:数据小太阳 更新时间:2023-10-29 04:12:46 24 4
gpt4 key购买 nike

我有一个文件拖放区来获取文件的数据内容。
如果我将 $scope.importData 设置为 null,则无法再在放置处理程序中分配数据。

$scope.handleDrop = function(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.dataTransfer ? evt.dataTransfer.files : evt.target.files,
file = files[0],
reader = new FileReader();

reader.onloadend = function(evt) {
var content = evt.target.result;
if('' !== content) {
$scope.importData = content; //will work as long you do not set $scope.importData to null
$scope.$apply();
}
};
reader.readAsText(file);
}
};

我发现问题可能出在 ng-include 上。如果我在没有包含的情况下这样做,它将起作用。

请尝试 Plunker...

http://plnkr.co/edit/BFOquRMLOqpL3arv1rtI?p=preview

最佳答案

ngInclude 创建一个新范围,该范围原型(prototype)上继承自其父范围,在您的 plunker 示例中,父范围是您的 pageCtrl 的范围。您的示例的问题在于,在 $scope.addSetReImport 中,您正在设置 var $scope = this; 并且在该上下文中 this 指的是 ngInclude 的作用域,而不是您的 pageCtrl 作用域,因此 $scope.importData = null; 使用 ngInclude 作用域上的属性有效地覆盖原型(prototype) importData 变量。以下来自 Chrome 控制台的屏幕截图说明了此覆盖,它来自 ngInclude 的 $scope:

enter image description here

所以你最终得到两个 importData 变量,一个位于你的 ngInclude 范围内并在你的模态模板中使用,它指向 null,第二个位于你的 pageCtrl handleDrop 函数期间使用的范围。由于 handleDrop 将更新 pageCtrl 范围内的 importData,因此它不会反射(reflect)在模板正在使用的 ngInclude 范围内设置的属性。

要使您的示例正常运行,只需从 addSetReImport 函数中删除 var $scope = this;,这可确保您引用的是 pageCtrl 的范围。这是一个带有工作示例的克隆插件:http://plnkr.co/edit/LvYGKqLlL9Pxq0X5slyM?p=preview

关于javascript - Angular 中的范围变量和 ng-include 不协调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882378/

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