Leon Leon - 1 year ago 56
AngularJS Question

Angular var used outside of function

a simple Angular / javascript question:

I have a form which uses two functions, one is executed "on click", the other "on submit":

$scope.onclickevent = function(files) {
$scope.imageFile = files[0];
console.log($scope.imageFile);
}

$scope.onsubmitevent = function(){
console.log($scope.imageFile); // herein lies the problem
}


The HTML is like this :

<div class="file-field input-field ">
<input type="file" name="file" onchange="angular.element(this).scope().onclickevent(this.files)"/>
</div>

<a href="" class="btn" ng-click="onsubmitevent()">Create</a>


How do I access $scope.imageFile from another function? Upon calling onsubmitevent, $scope.imageFile is "undefined". Yet the console.log in the first function shows it as set.

$rootscope is an option, but it seems wrong to set this globally.
Parsing the variable back to the html and then back to the second function also seem long-winded and cumbersome.

Answer Source

If you first call onclickevent, it will set the $scope.imageFile to files[0], and then you can get it from the onsubmitevent via $scope.imageFile

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download