2016-06-23 33 views
5

Trong Góc 1,5, tôi muốn tải mẫu qua lời hứa tùy chỉnh. Đoạn mã ví dụ mà tôi muốn chạy làTải mẫu thành phần dạng góc 1,5 theo lời hứa

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() { 

} 
}); 

Lý do tôi muốn làm điều này là để tải các mẫu từ một iframe proxy.

Nếu có cách nào để cung cấp trình phân giải mẫu tùy chỉnh của tôi cho lời hứa sẽ quá đủ.

+0

Nhìn bài http://stackoverflow.com/questions/22189298/angularjs-returning-a-promise-in-directive-template-function này. Nó có vẻ là cùng một vấn đề với chỉ thị. Tôi nghĩ bạn có thể thử một sự chấp thuận tương tự – Silvinus

Trả lời

3

Tôi đã giải quyết vấn đề bằng cách thay thế $ templateRequestService của góc sử dụng trang trí.

Xem ví dụ mã bên dưới:

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; 
    }]); 

}]); 
+0

Bạn có thể sử dụng trả lại $ q.when() để tránh sử dụng trì hoãn trực tiếp. – Vitalii

Các vấn đề liên quan