【问题标题】:UI-Router, how to get the name of the 'state' And How send it to the function That brings Template stateUI-Router,如何获取“状态”的名称以及如何将其发送到带来模板状态的函数
【发布时间】:2015-11-24 12:02:47
【问题描述】:

我从角度开始

我想写一个函数,为每个state带来模板

而且只是在需要的时候。作为“延迟加载”的原理

然后在第一次使用时将其保存在缓存中

我写了这段代码 但是我有错误,我不知道我错了什么, 有些东西我在角度上不明白,所以我理解我的代码中的问题

这是我所有的代码:

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>

【问题讨论】:

    标签: angularjs angular-ui-router angular-ui state


    【解决方案1】:

    有updated and working example

    我们能做的最好的就是结合两个强大的功能:

    1. UI-Router templateProvider 动态构建模板路径和
    2. angular $templateRequest 非常聪明,可以为我们加载和缓存模板

    这里是templateUrl 替换:

    // instead of templateUrl
    templateProvider: ['$templateRequest', '$stateParams', 
        function($templateRequest,$stateParams){
          var pathToTemplate = 'pagesTemplate.html';
    
          // do some magic with pathToTemplate
    
          return $templateRequest(pathToTemplate);
    
        }],
    

    查看here in action

    还要注意这些:

    【讨论】:

    • 我为您提供了更新后的 plunker 的链接.. 它在那里
    • 还有另一个更新的 plunekr plnkr.co/edit/lbSagZdrQSRq2xuF55AQ?p=preview - 它现在与两个州一起工作.. 类似的方式,希望对您有所帮助
    • 很高兴看到这一点;)如果您认为此答案有帮助,您可以接受。享受 UI-Router
    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2019-06-05
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多