Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js - Passing $scope into jQuery function

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() ?

like image 768
alyx Avatar asked Jan 12 '23 18:01

alyx


2 Answers

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

like image 122
Bastien Caudan Avatar answered Jan 21 '23 11:01

Bastien Caudan


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

like image 28
massintha Avatar answered Jan 21 '23 11:01

massintha