javascript - 无法获取 $scope 内设置的值

标签 javascript angularjs angularjs-scope

在我的 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/

相关文章:

angularjs - 无法清除表格

javascript - 模板中的 Angular.js 格式分钟

angularjs - 在 angular.js 中缓存并设置范围值

AngularJS:具有路由的多个 View 而不会丢失范围

javascript - 当我在 AngularJS 中输入搜索文本时,如何关闭或打开多个过滤器

javascript - AngularJS - 无法在 View 中访问检索到的 JSON 数据

javascript - Selection.addRange() 已弃用 - 如何解决错误

javascript - React 中的尖括号和星号是什么意思?

javascript - 单击菜单更改文本

javascript - DOM4 中已弃用 CDATA 节节点