Nếu bạn muốn tiêm phụ thuộc (giả sử từ một dịch vụ) để gọi một dạng hàm trong các tuyến đường (config) như hình dưới đây templateProvider.getTemplate ('about')
.state('index.about', {
url: "/about",
templateUrl: templateProvider.getTemplate('about'),
controller: 'AboutCtrl',
controllerAs: 'about',
data: {pageTitle: 'About Us Page'}
})
Bạn phải tạo ra một nhà cung cấp. Không phải Dịch vụ hay Nhà máy.
Dưới đây là một ví dụ thực tế của một nhà cung cấp mà tạo ra con đường mẫu từ tên:
(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';
}
};
})();
Việc sử dụng nhà cung cấp như vậy trong các tuyến đường (config) sẽ như sau:
(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');
};
})();
Lưu ý VIP:
để tiêm nhà cung cấp, bạn phải postfix nó với xxxProvider (tên đó của nhà cung cấp không nên được postfixed, chỉ trên tiêm trong .config).
bạn có thể tiêm '$ http' cho cấu hình chỉ ví dụ như' $ httpProvider': https://docs.angularjs.org/api/ng/provider/$httpProvider – dewd