skip to Main Content

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
    }
});

2

Answers


  1. 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…

    Login or Signup to reply.
  2. In ES6 controllers can be defined as standard Classes. If you define them this way it is easy to import and use them outside of angular as well.

    class MainController {
    
      constructor(searchService) {
        this.title = 'Hello World';
      }
    
      myFunction () {
        // do things...
      } 
    
      someOtherFunction () {
        // do things...
      }
    
    }
    export { MainController }
    

    in app.js (or whatever)

    import { someFunction, someOtherFunction } from "web/static/js/MainController";
    

    then you can access it with:

    let result = someFunction();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search