问题
I start in angular
And I want to write a function that will bring template For each state
And just when need it. As the principle of "Lazy loading"
And after that keep it in the cache when it's the first time
I wrote this code But I have errors, and I do not know what I'm wrong, Some things I did not understand in angular so I understand the problematic in my code
this is all my code :
http://plnkr.co/edit/qzKJUwNImVX8EGb3ymnT?p=preview
var app = angular.module('myApp', ['ui.router']);
var getTemplate = function(name) {
templates = {pages: 'content of pagesTemplate.html. I very wish !!'};
if (name in templates) {
return templates[name];
}
$http.get(name + 'Template.html' ).then(
function(response){
templates[name] = response.data;
return templates[name];
}
);
};
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('pages', {
url: '/:page',
templateUrl: getTemplate(), // Exist in line 18 ▲
// Here I want to build a function or calld a function
// To bring me the template of the page
// But I want it will be stored in the cache, if it comes first time
// And next time I will take it from the cache by the name of the 'state' ('pages').
controller: function($stateParams) {
alert($stateParams.page);
// And here I want to receive From the server The content of the page By $stateParams.page
}
})
});
<a ui-sref="pages({ page: 'home' })">Home</a>
<div ui-view=""></div>
回答1:
There is updated and working example
The best we can do is to combine two great features:
- UI-Router
templateProvider
to dynamically built template path and - angular
$templateRequest
which is so smart, that it does load and caches templates for us
here is the templateUrl
replacement:
// instead of templateUrl
templateProvider: ['$templateRequest', '$stateParams',
function($templateRequest,$stateParams){
var pathToTemplate = 'pagesTemplate.html';
// do some magic with pathToTemplate
return $templateRequest(pathToTemplate);
}],
Check it here in action
And also observe these:
- Using templateRequest in angular + typescript ($templateRequest not a function)
- ui router nested views condtions
来源:https://stackoverflow.com/questions/33893222/ui-router-how-to-get-the-name-of-the-state-and-how-send-it-to-the-function-th