Angular ocLazyLoad 与ui-router的配合使用

1.resolve

state(配置路由时)的resolve参数:

resolve:object,将会被注入controller去执行的函数,<string,function>形式。

基于uiRouter的resolve是在加载controller和template之前所执行的一系列操作,它帮助我们初始化我们所要前往的那一个视图。只有be solved(操作完成),controller才会被实例化。因此,我们可以在resolve步骤里面加载我们所需要的controller。

$stateProvider.state('index', {
  url: "/", // root route
  views: {
    "lazyLoadView": {
      controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
      templateUrl: 'partials/main.html'
    }
  },
  resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
    loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
      // you can lazy load files for an existing module
             return $ocLazyLoad.load('js/AppCtrl.js');
    }]
  }
});

resolve中加载AppCtrl.js,但是请求都是异步的,返回的顺序不是按照顺序来的。在loadMyCtrl中需要调用AppCtrl里面的getBookById()方法。这个时候虽然在load里面已经加载AppCtl.js,但是在loadMyctl中是无法使用get()方法,
所以在loadMyctl对象中,所以必须重新加载AppCtl.js。这个时候就需要$injector中的get()方法。
$stateProvider.state('index', {
  url: "/",
  resolve: {
    loadMyCtl: ['$ocLazyLoad', '$injector', function($ocLazyLoad, $injector) {
      return $ocLazyLoad.load('js/ServiceTest.js').then(function() {
        var $serviceTest = $injector.get("$serviceTest");
        $serviceTest.get();
      });
    }]
  }
});