4

我有两个 html 页面,snippet1.html& snippet2.html。我想在我的指令中使用它们。因为我将使用单个指令添加多个模板。

<script>我通过在标签中添加 html 模板来尝试这个东西,type="text/ng-template"并像下面一样给他们。

<script type="text/ng-template" id="snippet1.html">
    <div>Here is Snippet one</div>
</script>

<script type="text/ng-template" id="snippet2.html">
    <div>Here is Snippet two</div>
</script>

然后我使用$templateCache.get('snippet1.html'). 此实现运行良好。

但在我的情况下,我需要从 html 本身加载它们,所以我决定通过 ajax 加载模板并制作$http cache: $templateCache

工作 JSFiddle

运行块

myApp.run(['$templateCache','$http', function($templateCache, $http){ 
  $http.get('snippet1.html',{ cache : $templateCache }); 
  $http.get('snippet2.html',{ cache : $templateCache }); 
}]);

但是在我的控制器内部$templateCache.get('snippet1.html')是未定义的。

我的问题是,为什么当我在<script>' tag & Why it don't work when I html inside$templateCache while making$http` ajax 调用中声明模板时它正在工作?

有问题的 Plunkr

谁能帮我解决这个问题?或者我在代码中遗漏了任何东西。

帮助将不胜感激。谢谢。

4

2 回答 2

6

这是一个有趣的问题,我可以提供一个有趣的解决方法以及我对正在发生的事情的想法。我认为可能存在更好的解决方案,但找到这样的解决方案也被证明是一个挑战。尽管如此,我认为主要问题只是你console.log($templateCache.get('snippet1.html'))的回归undefined,因为你$http.get的 ' 没有首先解决的竞争条件。

检查$templateCache的 api ,我找不到任何有用的方法来了解模板何时通过 ajax 请求解析。要查看简单的问题,请在指令中运行它以查看有关当前存储在您的$templateCache

console.log($templateCache.info())

结果是

对象{id:“模板”,大小:0}

为了观察问题的核心,在指令中运行相同的 JS,但有这样的超时

setTimeout(function() {
    console.log($templateCache.info())
}, 1000);

结果是

对象{id:“模板”,大小:2}

很有趣,所以他们就在里面……但现在要处理好他们是个挑战。我制定了以下解决方法,至少暂时给我们一些东西。注入$q$rootScope注入您的.run功能

myApp.run(['$templateCache', '$http', '$q', '$rootScope', function($templateCache, $http, $q, $rootScope){ 
    $q.all([
        $http.get('snippet1.html',{ cache : $templateCache }),
        $http.get('snippet2.html',{ cache : $templateCache }) 
    ]).then(function(resp){
        $rootScope.templateCache = resp
    })
  }]
); 

var检查这个,你会注意到我在我们$rootScope的对象上放置了一个任意$rootScope.templateCache的,目的是$watch在我们的指令中放置一个。然后在我们的指令中,$templateCache当我们知道有一个值 on 时,让我们调用我们的$rootScope.templateCache,表明$q服务已经解决了我们的承诺

link: function(scope, element, attrs) {
    scope.$parent.$parent.$watch('templateCache', function(n, o) {
        if(n) {
            element.append($compile($templateCache.get('snippet1.html')[1])(scope));
        }
    });
}

嘿看!我们的模板指令正确呈现。看起来很老套scope.$parent.$parent是因为在这个指令中,我们已经隔离了我们的scope,现在需要爬一些梯子来获得定义的值$rootScope

我希望我们能找到一种更简洁更简洁的方式吗?当然!但是,希望这可以确定发生这种情况的原因以及目前启动和运行的可能方法。下面提供了工作 plunker。

Plunker 链接

编辑

这是一种完全不同的方法来解决这个问题,它涉及手动引导

var providers = {};

var $injector = angular.injector(['ng']);

var myApp = angular.module('myApp', []);

$injector.invoke(function($http, $q, $templateCache, $document) {
    $q.all([
        $http.get('snippet1.html',{ cache : $templateCache }),
        $http.get('snippet2.html',{ cache : $templateCache }) 
        ]).then(function(resp){
            providers.cacheProvider = $templateCache;
            angular.bootstrap($document, ['myApp']);
        });
    });

myApp
.controller('test',function() {
})
.directive('myTemplate', function ($templateCache, $compile) {
    return {
        restrict: 'EA',
        scope: {
            snippets: '='
        },
        link: function(scope, element, attrs) {
            element.append($compile(providers.cacheProvider.get('snippet1.html')[1])(scope));
        }
    };
});

更新的 Plunker

于 2015-02-12T22:03:56.673 回答
3

这是预期的行为。当您在脚本标签中包含模板时,angular 会在引导过程中找到它,并在任何代码运行之前将其添加到缓存中。这就是为什么它在您的指令中可用。

当您使用 $templateCache.put() (或使用 $http.get 来检索您在代码中指定的 html 文件时,angular 必须使用 ajax 来解析模板。当请求“进行中”时,模板缓存对此一无所知-该文件仅在收到响应后才添加到模板缓存中。

由于您的指令作为第一个摘要周期的一部分运行(在启动时),缓存中永远不会有任何远程文件,因此您会看到您看到的错误。

做你想做的事情的“正确”方法是不要直接使用 $templateCache ,而是使用 $http 服务来请求远程模板。如果原始响应已返回,$http 将为您调用 $templateCache.get。如果没有,它将返回与原始 $http 请求生成的相同的承诺。

这样做,将不需要使用 $timeout 或 $watch。一旦模板可用,就会使用 Promise 编译模板。

myApp.controller('test',function(){})
    .directive("myTemplate", function ($http, $compile) {
    return {
        restrict: 'EA',
        scope: {
            template: '&?myTemplate',
            src: '&?'
        },
        link: function(scope, element, attrs) {
            $http.get(scope.template() || scope.src()).then(function(result) {
                element.append($compile(result.data)(scope));
            });
        }
    };
});

<my-template src="snippet1.html"></my-template>

或者

<div my-template="snippet1.html"></div>

这是一个有效的 Plunk

编辑:没有 $compile 和 $http 的替代方案

myApp.controller('test',function(){})
    .directive("myTemplate", function ($http, $compile) {
    return {
        restrict: 'EA',
        scope: {
            snippets: '='
        },
        template: 'snippet1.html',
        link: function(scope, element, attrs) {

        }
    };
});

至于你的最后一个问题(为什么你必须使用 [1] 来获取 html - $http 服务不仅在缓存中存储 html - 它存储可能包含承诺或元素的数据结构(如果从脚本加载)标记)。既然它知道放入了什么,它就知道如何取出它。当你把东西短路时,你只是在猜测。

长话短说 - 不要使用 $templateCache 自己解析模板。

编辑:来自 $http 的代码演示了可能存储在缓存中的不同类型的数据。

if (cache) {
    cachedResp = cache.get(url);
    if (isDefined(cachedResp)) {
      if (isPromiseLike(cachedResp)) {
        // cached request has already been sent, but there is no response yet
        cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
      } else {
        // serving from cache
        if (isArray(cachedResp)) {
          resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
        } else {
          resolvePromise(cachedResp, 200, {}, 'OK');
        }
      }
    } else {
      // put the promise for the non-transformed response into cache as a placeholder
      cache.put(url, promise);
    }
  } 
于 2015-02-13T08:01:22.240 回答