So here's the deal; I have this $watch
which is set on a file input, and checks if a new file is selected. After a new file (usually an image) is selected, thus triggering the watch, I want these 3 things to happen:
1-a flag ( imgAvailable
) be set to 1;
2-a preview of image be shown; which needs image to be saved into $rootScope.img2
;
3-selected image be pushed to an array ( $rootScope.imgs
or myTestVariable
);
The first two happen, however, the third one does not.
This is my watch; Note that this watch runs in main controller of this page, rootScope.imgs = []
was defined in the controller of previous page, and var myTestVariable = rootScope.imgs
$scope.$watch('file', function(newfile, oldfile, scope) {
if(angular.equals(newfile, oldfile) ){
return;
}
scope.$root.img2 = image;
myTestVariable.push(image);
scope.imgAvailable = true;
},
function (newfile,oldfile,scope){
scope.$apply(function() {
scope.$root.img2 = newfile;
scope.$root.imgs.push(newfile);
});
});
This is the input which the $watch
is set on:
<input type="file" fileinput="file" filepreview="filepreview" id="myIngSelector"/>
Edit: I though I would be irrelevant, but fileinput
is this directive:
.directive("fileinput", [function() {
return {
scope: {
fileinput: "=",
filepreview: "="
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
scope.fileinput = changeEvent.target.files[0];
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope.filepreview = loadEvent.target.result;
scope.$root.img2=scope.fileinput;
});
}
reader.readAsDataURL(scope.fileinput);
});
}
}
}])
After I select image and check my inspect page, both myTestVariable
and rootScope.imgs
are equal to [], so basically nothing has happened and no img was pushed in any of these two arrays.
What I have tried:
- defining
rootScope.imgs
in this controller; no change. - calling an external function instead of
$apply
; no change; - I actually hoped to be able to trace it line by line, however I gained no success. :D - change
rootScope.imgs
toscope.imgs
; results in undefined; - push image to
rootScope.imgs
outside watch manually; It works. So generally that images can be pushed intorootScope.imgs
. It just does not happen in the watch.
Please pay attention that the $watch
is not on array itself; It is on a file input.
What should I do to be able to push objects into array inside a $watch
on that object?
Any amount of help will be highly appreciated.