2016-06-23 8 views
5

In Angular 1.5, voglio caricare il modello tramite promessa personalizzata. Il codice di esempio che vorrei fare funzionare èCarica modello angolare 1.5 componenti tramite promessa

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

} 
}); 

Il motivo che voglio fare è quello di caricare il modello da un iframe proxy.

Se c'è un modo per fornire il mio resolver template personalizzato per una promessa che sarebbe troppo sufficiente.

+0

Guarda questo post http://stackoverflow.com/questions/22189298/angularjs-returning-a-promise-in-directive-template-function. Sembra essere lo stesso problema con la direttiva. Penso che tu possa provare un simile approcio – Silvinus

risposta

3

Ho risolto il problema sostituendo $ templateRequestService di angolare utilizzando decoratore.

vedere il codice esempio riportato di seguito:

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

Puoi usare return $ q.when() per evitare di usare direttamente il differimento. – Vitalii