Mark
Mark

Reputation: 15

javascript execution order with AngularJS

I am going to maintain someone else's website, and I found a block of code like this (I have removed a lost of code to make example of code simpler)

    var Application = (function ($, global) {
    'use strict';
    global.site = global.site || {};
    global.site.App = App;

    function App() {
       // code removed
    }

    App.getState = function () {
        return 'standard';
    };

    App.setState = function () {
        // Set current state on load
        site.App.currentState = site.App.getState();
    };

    //a lot of code was removed

    return {
        init:function(){

            global.site.app = new global.site.App();

            // Set browser sate on load
            site.App.setState();
            console.log('Application: site.App.currentState', site.App.currentState);  
        }
    }

}(window.jQuery, window));

$(Application.init);

var siteApp = angular.module('siteApp', []);
siteApp.controller('AppController', function() {
      console.log('AppController: site.App.currentState', site.App.currentState);
});

The problem is that even though I put var Application = (function ($, global) {...}(window.jQuery, window)); above angularjs module, the angularjs module run first. And I have to admit that I don't fully undenstand how the var Application ... design pattern work, so my questions are:

  1. How can I make $(Application.init); run first ?.
  2. What kind of design pattern is that (Application.init) , so I can googel it and try to understand it

any helps are appreciated.

Upvotes: 0

Views: 70

Answers (2)

malix
malix

Reputation: 3582

A) That code is overly convoluted and should probably be moved to an Angular service/value/factory

B) To manage code order, you can also remove your ng-app="App" and bootstrap Angular yourself:

  angular.element(document).ready(function () {
    Application.init();
    angular.bootstrap(document, ['App']);
  }

C) That code uses the module pattern, e.g. http://toddmotto.com/mastering-the-module-pattern

Upvotes: 0

Sandeeproop
Sandeeproop

Reputation: 1776

You can try removing

$(Application.init)

and direct calling

Application.init() 

Upvotes: 2

Related Questions