2

In time I want to convert my entire app to AngularJS, but I'll need to do it bit by bit. So for the time being, I just want to be able to make this work.

I want to be able to call the AngularJS loadData() function on a jQuery click event. But I am not sure how to do it. Any help is appreciated, thank you.

I have this jQuery code:

// When back is pressed
$('#backward').click(function() {
    index--;

    // Re load data
    angular.element(document.getElementById('myController')).scope().loadData();
});

This AngularJS code:

.controller('MyController', function($log, $scope, myService) {
    var loadData = function() {
        ...
    };

    var $scope.loadData = loadData;

And this HTML:

<body id="myController" ng-controller="MyController">
3
  • 1
    Is this your actual code var $scope.loadData = loadData;? This is a syntax error. Commented Nov 14, 2014 at 2:32
  • Strangely enough, my code was actually var $scope.loadData = loadData(); and when I changed it to the one in your message - it started working! Commented Nov 14, 2014 at 2:51
  • I got the answer from following link : How to call angular js function controller from jquery in page Commented Dec 20, 2016 at 10:39

1 Answer 1

0

Use ng-click=loadData on the #backward element.

If #backward is not within the scope of myController, you can use a service instead and have ng-click trigger a method on the correct controller that calls a method on the service.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Like I said I need to make these changes piece by piece though - there are other jQuery areas I need to be able to call that AngularJS code from (that button was just one example). Thanks though, because that does help me in that area - but I have timers etc that also call it, so if there is a way I can call AngularJS code from jQuery I would be very interested to know.
@b85411 Generally you can't do this because everything has to be within Angular so the digest cycle and data bindings will work properly. Unfortunately I'm not too sure that you will be able to do this incrementally; it may be better to try to change self-contained pieces of the app to use Angular bit by bit instead.
It's a hack, but I managed to get it working (see messages above). But yes, you're right - I think I'll just need to try and change self contained pieces over in one hit as you suggest. It will be cleaner that way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.