UI-Router, how to get the name of the 'state' And How send it to the function That brings Template state

 ̄綄美尐妖づ 提交于 2020-01-07 03:07:07

问题


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:

  1. UI-Router templateProvider to dynamically built template path and
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!