5

在 Angular 1.5 中,我想通过自定义承诺加载模板。我想运行的示例代码是

var module = angular.module("myApp", []);
module.component("component", {
template: ["$q", function ($q) {

    var defer = $q.defer();

    setTimeout(function () {
        defer.resolve("<p>Hello world</p>");
    }, 100)
    return defer.promise;
}],
controller: function () {

}
});

我想这样做的原因是从代理 iframe 加载模板。

如果有任何方法可以为我的自定义模板解析器提供足够的承诺。

4

1 回答 1

3

我通过使用装饰器替换 angular 的 $templateRequestService 解决了这个问题。

请参见下面的代码示例:

module.config(["$provide", function ($provide) {

$provide.decorator("$templateRequest", [
    "$delegate", "$q", // DI specifications
    function ($delegate, $q) {

        // replace the delegate function 
        $delegate = function (tpl) {
            var defer = $q.defer();
            // convert the tpl from trustedvaluetoken to string
            if (typeof (tpl) !== "string" || !!$templateCache.get(tpl)) {
                tpl = $sce.getTrustedResourceUrl(tpl);
            }
            // make proxy call and resolve the promise;

            // Make an async call
            return defer.promise;
        }
        // return the modified delegate function
        return $delegate;
    }]);

}]);
于 2016-06-24T06:22:23.913 回答