If you want to call an external function (in your case, a Utility function), enter your routes (.config) as shown below: templateProvider.getTemplate ('about')
.state('index.about', { url: "/about", templateUrl: templateProvider.getTemplate('about'), controller: 'AboutCtrl', controllerAs: 'about', data: {pageTitle: 'About Us Page'} })
You cannot create a Service or Factory for this. Instead, you should create a provider.
Here is a real example of a provider that generates a template path from a name:
(function () { 'use strict'; angular .module('mega-app') .provider('template', provider); function provider(CONSTANT) { // The provider must include a $get() method This $get() method // will be invoked using $injector.invoke() and can therefore use // dependency-injection. this.$get = function () { return {} }; /** * generates template path from it's name * * @param name * @returns {string} */ this.getTemplate = function (name) { return CONSTANT.TEMPLATES_URL + name + '/' + name + '.html'; } /** * generates component path from it's name * @param name * @returns {string} */ this.getComponent = function (name) { return CONSTANT.COMPONENTS_URL + name + '.html'; } }; })();
Using such a provider in routes (.config) will be as follows:
(function () { 'use strict'; angular .module('mega-app') .config(routes); function routes($stateProvider, $urlRouterProvider, templateProvider) { $stateProvider //---------------------------------------------------------------- // First State //---------------------------------------------------------------- .state('index', { abstract: true, url: "/index", templateUrl: templateProvider.getComponent('content'), controller: 'IndexCtrl', controllerAs: 'index', }) //---------------------------------------------------------------- // State //---------------------------------------------------------------- .state('index.home', { url: "/home", templateUrl: templateProvider.getTemplate('home'), controller: 'HomeCtrl', controllerAs: 'home', data: {pageTitle: 'Home Page'} }) //---------------------------------------------------------------- // State //---------------------------------------------------------------- .state('index.about', { url: "/about", templateUrl: templateProvider.getTemplate('about'), controller: 'AboutCtrl', controllerAs: 'about', data: {pageTitle: 'About Us Page'} }) //---------------------------------------------------------------- // Default State //---------------------------------------------------------------- $urlRouterProvider.otherwise('/index/home'); }; })();
Note for VIP:
to enter a provider, you must send it using xxxProvider (this provider name should not be postfix, only when injected into .config).