Ad

How Do I Call An Angular JS Function From Outside The Controller Via Javascript Or Jquery?

- 1 answer

I am working on a project and using both Jquery and AngularJS. Jquery - primarily for the plugins already available. Angular - for the ease of working on forms and objects and DOM manipulation.

I have a plugin ( https://github.com/VinceG/twitter-bootstrap-wizard) where custom events are defined like - onShow, onFinish, onNext etc. These events get triggered when the user does something.

How do I call an AngularJS function from one of these functions?

Code From Plugin

   $(document).ready(function() {
        $('#rootwizard').bootstrapWizard({
            tabClass: 'nav nav-pills',
            onNext: function(tab, navigation, index) {

               //I want to access the myFunction declared 
                //inside the AngularJS code and pass 'index' to it
            }
      });
    });

AngularJS code

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

    $scope.myFunction = function(index) {
        // do something with index
    }
});
Ad

Answer

the simplest way for doing this would be retriving the scope of the controller from some element and then calling it's method like:

var myScope = angular.element($('#someElement')).scope();
myScope.doSomething(); // make sure you also invoke the $scope.$apply() to start the digest process. 

But, think first, is this what you really want to do, I find this way bit hacky, also IMO mixing jQuery and Angular is not a good thing in the long run...

Ad
source: stackoverflow.com
Ad