在我的angularjs应用程序中,我有以下行为异常的程序段。
我已经在功能块中声明了变量,但是尽管在功能块中设置了值也无法访问这些值。我要去哪里错了。
$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);
});
有关角度生命周期的更多信息:http : //onehungrymind.com/notes-on-angularjs-scope-life-cycle/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句