2015-03-31 35 views
3

我有一個app.run(appRun);在我的代碼中,但我不清楚爲什麼它需要。該appRun功能有一些基本的東西在裏面,但看起來沒有像它不能在AppController的。是什麼app.run(appRun);用於AngularJS?

我已經在此使用的應用程序控制器:

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

希望一些可以幫助解釋我的區別。由於

+0

嘗試在看這個 http://stackoverflow.com/questions/20663076/angularjs-app-run-documentation – 2015-03-31 11:01:27

回答

4

您可以找到細節here有關文件app.run()模塊。

據我所知,已經配置的所有服務和噴油器創建後執行的run方法。我們把這些東西放到運行塊中,這對於進行單元測試並不那麼容易。

以下是我的網站的示例: 此示例基於django和angularjs網站,在這裏我已配置我的應用程序。

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; 

}]);