I'm using jQuery File Uploader through Angular.js. I need to pass the server's response from the image upload to the Angular $scope, but I can't access the $scope within the done
function:
function LandmarkNewCtrl($location, $scope, db) {
$('#fileupload').fileupload({
url: '/api/upload',
dataType: 'text',
done: function (e, data) {
$scope.landmark.avatar = data.result;
}
});
}
Getting "Uncaught TypeError: Cannot read property 'landmark' of undefined" errors.
How do I pass $scope into the done: function()
?
You must not access HTML in angular controller. You should use a directive to do what you want :
angular.module('yourModule').directive('fileupload', function() {
return function($scope, $element) {
$element.fileupload({
url: '/api/upload',
dataType: 'text',
done: function (e, data) {
$scope.landmark.avatar = data.result;
$scope.$apply();
}
});
}
});
The done function is triggered by jQuery so you need to perform a $sope.$apply(), to force angular to refresh scope bindings.
Then use this directive in your template :
<div ng-app="yourModule">
<div fileupload>Fileupload</div>
</div>
More information on wrapping a jQuery component : Beginner questions with AngularJS and directives - wrapping a jQuery component
It's more recommended to do something like
angular.element('#fileupload').fileupload({
url: '/api/upload',
dataType: 'text',
done: function (e, data) {
$scope.landmark.avatar = data.result;
}
});
it should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With