AngularJS config run 及區別和例子

1、config方法html

  在模塊加載階段,對模塊進行自定義配置html5

  config能夠注入$stateProvider, $urlRouterProvider, $controllerProvider, $provide, $httpProvider等等provider,web

  config的工做流程:ajax

  新建一個模塊,這個模塊中有一個服務,一個自定義指令express

 var app = angular.module("myApp", []);  

  app.fatory('myFactory',function(){

    //利用工廠生產  建立一個 服務

    var service = {};

    return service;

  });

  app.directive('myDirectiive',function(){

    //建立 一個 自定義指令

    return {

      template:'<div><button>click me</button></div>'

    }

  });

   angularJS自動編譯後的流程是這樣的:數組

var app = angular.module('myApp',[]);
  app.config(function($provide,$compileProvider){
    $provide.factory('myFactory',function(){
    var service = {};
    return service;
    });
    $compileProvider.directive('myDiretive',function(){
      return {
        template:'<div><button>click me</button></div>'
      }
    });
  });

  在模塊上添加的服務,指定等,實際上都是在config階段配置的。瀏覽器

2、run方法微信

  是應用中最早執行的方法,相似於main方法,run方法只會在angular啓動的時候運行一次,定義全局的數據或邏輯,對全局做用域起做用,$rootScope上內容在多個控制器之間能夠共享。例如,註冊一個全局的事件監聽器。每次路由發生變化時候,都執行一個函數來驗證用戶的權限。cookie

angular.module('myApp', ['ngRoute'])

  .run(function($rootScope, AuthService) {

     $rootScope.$on('$routeChangeStart', function(evt, next, current) {

       // 若是用戶未登陸  

      if (!AuthService.userLoggedIn()) {

         if (next.templateUrl === "login.html") {

          // 已經轉向登陸路由所以無需重定向

        } else {

          $location.path('/login');

        }

      }

    });

  });

 

3、區別app

一、執行順序不一樣

  config先執行,run後執行。另外,ng啓動階段是 config-->run-->compile/link

二、注入服務類型不一樣

  config裏容許注入的是providerconstance(常量)run裏容許注入的是provider和constant,還能夠是factory,service,value

服務/階段 provider factory service value constant
config階段 Yes No No No Yes
run 階段 Yes Yes Yes Yes Yes

4、例子

一、config方法例子

  (1)、改變表達式符號

  對$interpolateProvider的服務進行了初始化的配置

var app = angular.module('myApp',[]);

  app .config(['$interpolateProvider',function($interpolateProvider){

     //要想初始配置,咱們首先要作模塊下面添加config方法,插入一個數組引入相應的供應商,以及相關的回調並注入

    //改變表達式頭部的符號

    $interpolateProvider.startSymbol('@@');

    //改變表達式尾部的符號

    $interpolateProvider.endSymbol('@@');

  }]);

  使用時雙@顯示而不是{{}}形式了

  <p>@@showText@@</p> 

  (2)、定義路由

var activityModule = angular.module('app.activity', [])
    .run(['$log', function ($log) {
        $log.debug('app.activity.run()...');
    }])
    .config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide', 'scriptDependencyProvider', '$stateProvider',
        function ($controllerProvider, $compileProvider, $filterProvider, $provide, scriptDependencyProvider, $stateProvider) {
            'use strict';
            activityModule.controller = $controllerProvider.register;
            activityModule.directive = $compileProvider.directive;
            activityModule.filter = $filterProvider.register;
            activityModule.factory = $provide.factory;
            activityModule.service = $provide.service;

            $stateProvider.state('activity', {
                name: 'activity',
                url: '/activity',
                controller: ['$scope', '$stateParams', function ($scope, $stateParams) {}],
                template: '<div ui-view></div>',
                resolve: scriptDependencyProvider.createDependenciesMap(scriptDependencyProvider.activity),
                deepStateRedirect: false,
                sticky: false
            }).state('activity.activityList', {
                url: '/activity/ActivityList',
                template: '<activity-list-view></activity-list-view>'
            });
        }
    ]);

  (3)、項目中實際配置 

app.config([
    '$logProvider', '$httpProvider', '$provide', '$stateProvider', '$urlRouterProvider', '$locationProvider', '$sceDelegateProvider',
    function ($logProvider, $httpProvider, $provide, $stateProvider, $urlRouterProvider, $locationProvider, $sceDelegateProvider) {
        // enable output $log.debug by default
        var isDebug = true;
        if (Global&& Global.isDebugEnabled) {
            isDebug = Global.isDebugEnabled();
        }
        $logProvider.debugEnabled(isDebug);

        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        $httpProvider.defaults.useXDomain = true;
        //initialize get if not there
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }
        //disable IE ajax request caching
        $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
        // extra
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';

        // configurate app root state
        var configurateRoute = function () {
            $urlRouterProvider.otherwise("/default");
            $locationProvider.html5Mode(false);
        };

        configurateRoute();

        $sceDelegateProvider.resourceUrlWhitelist(['**']);

        //$routeProvider
        //    .when('/error', { templateUrl: '/app/myframework/views/error-view.html' })
        //    .when('/about', { templateUrl: '/app/myframework/views/about-view.html' })
        //    .otherwise({
        //        redirectTo: '/'
        //    });

    }
]);

二、run方法例子

(1)、瀏覽器判斷

  定義一個全局邏輯,供應用的不一樣部分使用

.run(['$rootScope', '$route', '$window', '$location', 'Position', '$cookies', 'Request', '$cookieStore',
  function($rootScope, $route, $window, $location, position, $cookies, request, $cookieStore) {
   //非微信的登錄
   $rootScope.isWeiXinLogin = function() {
    //判斷是否微信登錄
    var ua = window.navigator.userAgent.toLowerCase();
    //console.log(ua); //mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13b143 safari/601.1
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
     console.log(" 是來自微信內置瀏覽器");
     return true;
    } else {
     console.log("不是來自微信內置瀏覽器");
     return false;
    }
   };
]);

  控制器中使用:

angular.module('autumnswind').controller('OrderCtrl', ['$rootScope', '$scope', 'Request', '$cookies', '$window', '$routeParams', '$location', 'Tool',
 function($rootScope, $scope, request, $cookies, $window, $routeParams, $location, tool) { 
if ($rootScope.isWeiXinLogin()) {
     ...
    }
   }
]);

(2)、定義全局數據

var app = angular.module('myApp',[]);
   app.run(['$rootScope',function($rootScope){
   $rootScope.name = 'hello';
   }]);

(3)、項目中例子

 run中代碼,最早執行,相似main方法

.run(['$log', '$templateCache', function ($log, $templateCache) {
        $log.debug('app.run()...');
        window.$templateCache = $templateCache;
        if (GlobalObj.templateCache) {
            for (var i = 0; i < GlobalObj.templateCache.templates.length; i++) {
                var template = GlobalObj.templateCache.templates[i];
                $templateCache.put(template.key, template.value);
            }
        }
    }]);
相關文章
相關標籤/搜索