4

I have an app.run(appRun); in my code but I am not clear on why it is needed. The appRun function has some basic things in it but nothing that looks like it could not be in the appController.

I already have an app controller that is used here:

<html lang="en" class="light"
      id="ngApp"
      ng-app="app"
      ng-cloak
      ng-controller="appController"

Hope some can help explain the difference for me. Thanks

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

5

You can find details here about app.run() module in documentation.

As I understand, the run method executed after all the services have been configured and injector has been created. we put the things inside the run block which is not that much easy for doing the unit-test.

Follows is the example of my site: This example based on django and angularjs site, here i have configured my app.

var AppName = angular.module('AppName', [

    'ngRoute',
    'ngCookies',

]);

// use for cookie
AppName.provider('myCSRF',[function(){

    var headerName = 'X-CSRFToken';
    var cookieName = 'csrftoken';
    var allowedMethods = ['GET'];

    this.setHeaderName = function(n) {
       headerName = n;
    }
    this.setCookieName = function(n) {
       cookieName = n;
    }

    this.setAllowedMethods = function(n) {
       allowedMethods = n;
    }
    this.$get = ['$cookies', function($cookies){
    return {
        'request': function(config) {
        if(allowedMethods.indexOf(config.method) === -1) {
            config.headers[headerName] = $cookies[cookieName];

            }
        return config;
    }
    }
    }];
}])


AppName.config(['$routeProvider',
        '$httpProvider','$interpolateProvider', function($routeProvider,$httpProvider,$interpolateProvider) {

    $interpolateProvider.startSymbol('{$');
    $interpolateProvider.endSymbol('$}');

    $httpProvider.interceptors.push('myCSRF');
    $httpProvider.defaults.xsrfCookieName = 'csrftoken'; 
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    $httpProvider.defaults.withCredentials = true;

    $routeProvider
    .when('/anyPage',{
        templateUrl: '/anyPage/'
    })
    .otherwise({
        redirectTo: '/'
    })


}])


AppName.run(['$http', '$cookies', function($http, $cookies) {

    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

}]);
Code_Crash
  • 734
  • 5
  • 22