I am working on browse and upload image functionality in my AngularJs application. I am using ng-image-compress for compressing image. I need to access a value of ng-src attribute in my controller whenever user selects an image from browse file dialog.
<input id="File1" type="file" accept="image/*" image="image1" ng-image-compress ng-model="image2"
resize-max-height="800" resize-max-width="800" resize-quality="0.7" resize-type="image/jpg"
onchange="angular.element(this).scope().uploadPhoto()" />
<br /><br />
<img ng-src="{{image1.compressed.dataURL}}" class="thumb" />
using above code, when I selects image, uploadPhoto() method called and selected image displays properly in img tag but I want to access ng-src value OR {{image1.compressed.dataURL}} in uploadPhoto() method.
NOTE :
<button ng-click="uploadPicture(image1.compressed.dataURL)">Submit</button>
If I try this, I got compressed dataUrl in uploadPicture() but I don't want this type of processing. please suggest appropriate way.
When you use plain JS onchange
event, you are out of the controller scope, that is why you have to call angular.element(this).scope()
to get back to the scope and execute uploadPhoto()
method.
Try to use Angular JS's ng-change
method:
<input id="File1"
type="file"
accept="image/*"
image="image1"
ng-image-compress
ng-model="image2"
resize-max-height="800"
resize-max-width="800"
resize-quality="0.7"
resize-type="image/jpg"
ng-change="uploadPhoto()" />
<br /><br />
<img ng-src="{{image1.compressed.dataURL}}" class="thumb" />
Now you should be able to access $scope.image1.compressed.dataURL
within your controller or service.
If you MUST stay with JS solution using 'scope()' function, try to pass needed info as argument to uploadPhoto()
function (if possible). Something like:
onchange="angular.element(this).scope().uploadPhoto(angular.element(this).scope().image1.compressed.dataURL)"
or using jQUery:
onchange="angular.element(this).scope().uploadPhoto(angular.element(this).next('img').attr('src'))"
UPDATE
here is solution using $scope.$watch
:
$scope.$watch('image1.compressed.dataURL', function(nVal) {
if (nVal) {
console.log('image1.compressed.dataURL', nVal);
}
});
here is a plunker: https://plnkr.co/edit/ArdhF6rPtREMCAzt7Eec?p=preview
in the plunker I populate another scope variable and use it on HTML