Dynamic templateUrl - AngularJS

后端 未结 4 457
南笙
南笙 2020-12-10 02:40

So as of Angular 1.1.4, you can have a dynamic template url. From here,

templateUrl - Same as template but the template is loaded from the specified URL

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 03:12

    Ran into a similar issue when creating a file upload fallback for browsers that don't support the File API (< IE10). Key difference is I needed the page to intelligently decide which template to display without the benefit of an attribute value to switch on.

    I ended up using the constant provider for my directive. Constants basically set up default parameters that can be injected anywhere in your directive. I simply let the constant call a function to determine browser support, then reference that value when I need to determine which template to pull. This is nice since 1) there's no attribute to reference and 2) it's available during the pre-link phase when you don't have access to the controller.

    (function () {
      var myDir = angular.module('myDir', []);
      myDir.constant('myDirConfig', {
          hasFileSupport: fileApiIsSupported()
        });
    
      myDir.directive('myDir', ['myDirConfig', function (myDirConfig) {
          return {
              templateUrl: function () {
                  if (myDirConfig.hasFileSupport) {
                      return 'pathToTemplate/html5.html';
                  } else {
                      return 'pathToTemplate/fallback.html';
                  }
              }
          };
      }];
    
      function fileApiIsSupported() { return (...); }
    })();
    

提交回复
热议问题