angularjs指令集模板URL动态 [英] angularjs directive set template url dynamically

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

问题描述

我创建与模板URL的指令。我想设置动态的基础上user_role的模板URL。任何想法?

我的继承人指令code:

  RatingRX.directiveheadermenu - >
  指令= {}
  directive.restrict ='E'
  directive.templateUrl =../assets/common/headerMenu{{user_role}}.html
  指示

和我想从控制器设置USER_ROLE。例如:

  $ scope.user_role = 1


解决方案

您可以通过一个函数来templateUrl选项,并返回将用作结尾模板URL字符串。

首先分配一个角色到元素的属性(其中的UserRole势必范围)为:

 < D​​IV我的指导性用户角色={{}的UserRole}>< / DIV>

然后指令可以把它读作:

  myApp.directive('myDirective',函数(){
  返回{
    限制:'A',
    templateUrl:功能(元素,ATTRS){
      返回../assets/common/headerMenu+ attrs.userRole +。html的;
    }
  }
});

更新:
过去,这与旧版本的前角工作。

< D​​IV NG-IF ====的UserRole管理员我的指示性用户角色=管理员>< / DIV>

I'm creating a directive with template URL. I want to set the template URL dynamically based on user_role. Any idea?

Heres my directive code:

RatingRX.directive "headermenu", ->
  directive = {}
  directive.restrict = 'E'
  directive.templateUrl = "../assets/common/headerMenu{{user_role}}.html"
  directive  

And I want to set user_role from the controller. Eg:

$scope.user_role = 1

解决方案

You can pass a function to the templateUrl option and return a string that will be used as a template url at the end.

First of all assign a role onto the element as an attribute (where userRole is bound to scope) as:

<div my-directive user-role="{{userRole}}></div>

Then the directive can read it as:

myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
    templateUrl: function(element, attrs) {
      return "../assets/common/headerMenu" + attrs.userRole + ".html";
    }
  }
});

Update: This used to work before with older version of Angular.

<div ng-if="userRole === 'admin'" my-directive user-role="admin"></div>

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

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