在我的 angularjs 应用程序中,我有以下行为奇怪的 block 。
我已在功能 block 中声明了变量,但尽管在功能 block 内设置了值,但仍无法访问这些值。我哪里出错了。
$scope.submitForm = function (isValid) {
var file = $scope.myFile;
var contents;
$scope.dataObj;
if (file) {
var r = new FileReader();
r.onload = function (e) {
console.log('Inside the file function ....');
contents = e.target.result;
$scope.$apply(function () {
$scope.fileReader = contents;
contents = contents.replace(/\r\n+/g, ",");
$scope.dataObj = {hosts: contents};
console.log($scope.dataObj); // prints the value twice
});
};
r.readAsText(file);
}
console.log("Printing the data objects .... ");
console.log($scope.dataObj); // prints undefined
}
最佳答案
$scope.$apply 将在稍后的周期中作为您的代码执行。因此 $scope.dataObj 将是未定义的(因为初始化 '$scope.dataObj;')并且 $scope.$apply 将在当前摘要周期之后运行。
我不知道任务结束后你想做什么,但也许观察者会帮助你?
$scope.$watch('dataObj', function(){
console.log($scope.dataObj);
});
有关 Angular 生命周期的更多信息:http://onehungrymind.com/notes-on-angularjs-scope-life-cycle/
关于javascript - 无法获取 $scope 内设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554051/