AngularJS: Returning a promise in directive template function

霸气de小男生 提交于 2019-12-11 01:26:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!