动态模板网址 - AngularJS [英] Dynamic templateUrl - AngularJS

查看:26
本文介绍了动态模板网址 - AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此从 Angular 1.1.4 开始,您可以拥有动态模板 url.从这里

<块引用>

templateUrl - 与模板相同,但模板是从指定的 URL 加载的.由于模板加载是异步的,编译/链接会暂停,直到模板加载完毕.

您可以将 templateUrl 指定为表示 URL 的字符串,也可以指定为带有两个参数 tElement 和 tAttrs(在下面的编译函数 api 中描述)并返回表示 URL 的字符串值的函数.

我如何利用它来生成基于指令的属性的动态模板?显然这不起作用,因为 tAttrs.templateType 只是字符串templateType"

templateUrl: 函数 (tElement, tAttrs) {如果(tAttrs.templateType == '搜索'){返回'/b/js/vendor/angular-ui/template/typeahead/typeahead.html'} 别的 {返回'/b/js/vendor/angular-ui/template/typeahead/typeahead2.html'}}

鉴于我无权访问范围,我该如何管理?

解决方案

以下也可以用于在 AngularJS 中创建动态模板:在您的指令中使用:

模板:'

'

现在您的控制器可以决定使用哪个模板:

$scope.getTemplateUrl = function() {返回/模板/角度/搜索";};

因为您可以访问您的范围参数,您还可以:

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

这样您的服务器就可以为您创建一个动态模板.

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?

解决方案

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.

这篇关于动态模板网址 - AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆