Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

angular ui - Dynamic templateUrl - AngularJS

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. Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded.

You can specify templateUrl as a string representing the URL or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the url.

How can I utilize this to generate a dynamic template based on, say, an attribute on my directive? Obviously this doesn't work, since tAttrs.templateType is simply the string "templateType"

templateUrl: function (tElement, tAttrs) {
  if (tAttrs.templateType == 'search') {
    return '/b/js/vendor/angular-ui/template/typeahead/typeahead.html'
  } else {
    return '/b/js/vendor/angular-ui/template/typeahead/typeahead2.html'
  }
}

Given that I don't have access to the scope, how do I manage this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following is also possible for creating dynamic templates in AngularJS: In your directive use:

template : '<div ng-include="getTemplateUrl()"></div>'

Now your controller may decide which template to use:

$scope.getTemplateUrl = function() {
  return '/template/angular/search';
};

Because you have access to your scope parameters, you could also do:

$scope.getTemplateUrl = function() {
  return '/template/angular/search/' + $scope.query;
};

So your server could create a dynamic template for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...