Angular.js - Passing $ scope to a jQuery function

I am using jQuery file loader through Angular.js. I need to pass the server response from loading the image into the Angular $ scope, but I cannot access the $ scope scope inside 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: Unable to read the" landmark "of undefined properties."

How to pass $ scope to done: function() ?

+4
source share
3 answers

It is more recommended to do something like

 angular.element('#fileupload').fileupload({ url: '/api/upload', dataType: 'text', done: function (e, data) { $scope.landmark.avatar = data.result; } }); 

he should work

+4
source

You should not access HTML in an angular controller. You must use the 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 executed function is launched by jQuery, so you need to execute $ sope. $ apply () to force angular to update the bindings to the region.

Then use this directive in your template:

 <div ng-app="yourModule"> <div fileupload>Fileupload</div> </div> 

Additional jQuery component packaging information: Getting started with AngularJS and directives - jQuery component wrapper

+5
source

The volume $ does not work inside the jQuery function, although it was called using the angular element, as suggested by keddour's answer.

Using a directive to call a function seems to be the correct answer.

For those who are looking for a simpler method for use in special circumstances (for example, in a dynamically loaded script), data exchange is also exchanged using a global variable. This violates some conventions, but Angular is really not perfect yet, and sometimes we have to resort to odd methods of solving problems.

Declare something like that in a global area.

 angularBridge = {}; 

Now in your controller (I assumed it in a dynamic script):

 demoApp.controlProvider.register('demoController', ['$scope', function($scope) { angularBridge.$demoScope = $scope; $scope.landmark.avatar = 0; }]); 

Now you can use this as an Angular controller or jQuery function to exchange data.

  function LandmarkNewCtrl($location, $scope, db) { $('#fileupload').fileupload({ url: '/api/upload', dataType: 'text', done: function (e, data) { angularBridge.$demoScope.landmark.avatar = data.result; } }); } 
0
source

Source: https://habr.com/ru/post/1494367/


All Articles