问题
As the title already says, I'd like to return a promise in the directive template function i.e.:
angular.module('someModule', [])
//...
.directive('someDirective', function() {
return {
//...
restrict: 'E',
template: function() {
var deferred = $q.defer();
//Some Async function which will call deferred.resolve
return deferred.promise; //Promise not supported by template property
}
};
});
Since the template property doesn't support this, is there any (simple) way to "emulate" that?
It looks like directive resolve is my best bet, but I'm having a hard time coming up with a nice way to apply the template loaded from a WebSocket in the resolve method.
My goal is to use a single WebSocket connection for all communication.
回答1:
You could try another approach:
app.run(function($templateCache, myTemplateLoader) {
myTemplateLoader.load('templateName').then(function(content) {
$templateCache.put('templateName', content);
});
});
And now you can simply use the templateUrl
property in your directives:
app.directive('someDirective', function() {
return {
// ...
templateUrl: 'templateName'
};
});
回答2:
In the resolve return the template and please follow dan wahlin's dynamic loading controller example and do the same like routeResolver.resolve function for your directive
http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx
Please let me know if it does not work i will create plunker and update it
来源:https://stackoverflow.com/questions/22189298/angularjs-returning-a-promise-in-directive-template-function