0

I'm trying to use ui-router with lazyload, from chrome I can see the required js is loaded but angular throws an error.

From the error I can tell the controller is not initialised, attached the router code:

var app = angular.module('aaaaa', ['oc.lazyLoad', 'ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/pages/dashboard');

  $stateProvider.state('index', {
    url: '/pages/:name',
    templateUrl: function($stateParams) {
      return 'templates/' + $stateParams.name + '.html';
    },
    controllerProvider: function($stateParams) {
      return $stateParams.name;
    },
    resolve: {
      loader: ['$ocLazyLoad', '$stateParams', function($ocLazyLoad, $stateParams) {
        var url = 'templates/controllers/' + $stateParams.name + '.js';
        console.log(url);

        return $ocLazyLoad.load({
          name: 'aaaaa',
          files: [url]
        });
      }]
    }
  });
});

Am I missing something?

daisy
  • 22,498
  • 29
  • 129
  • 265

2 Answers2

0

I would refactor your resolve.loader function as such:

loader: ['$ocLazyLoad', '$stateParams', function($ocLazyLoad, $stateParams) {
  var url = 'templates/controllers/' + $stateParams.name + '.js';

  return $ocLazyLoad.load(url).then(function () {
    return $stateParams.name;
  });
}]

Now, when ocLazyLoad has successfully loaded your controller code, we return the name of your controller (I'm assuming it's actual name matches that of $stateParams.name, as that is how you are referring to it in the controllerProvider).

And then in the controllerProvider:

controllerProvider: function (loader) {
  return loader;
}

controllerProvider nowadays accept the resolved values, not just stateParams - as per the following commit: ui-router#851f8e46.

This was introduced in 0.2.14 and has since been changed again, it now has support for resolved values in the templateUrl function aswell.

So as an aside, you could pass loaded into your templateUrl function as opposed to `$stateParams.name if you upgrade to 0.2.15. One value to rule 'em all?


For the heck of it, I would put a debugger statement at the top of your controllerProvider function beforehand to inspect the $stateParams.name and ensure it is the same as that of $stateParams.name inside the resolve.loader function. For the heck of it.


Also, it could prove very helpful to see the error thrown, the dev console output as well as the implementation details of your controller / module.

0

Problem resolved.

In the separate controller file, you can't write this,

app.controller ('xxx', [ ... ]);

Instead, use

angular.module('xxxx').controller ('xxx', [ ... ])

I don't know why yet, but it worked.

daisy
  • 22,498
  • 29
  • 129
  • 265