angularjs指令动态设置模板url

标签 angularjs angularjs-directive angularjs-scope

我正在使用模板 URL 创建一个指令。我想根据 user_role 动态设置模板 URL。任何的想法?

这是我的指令代码:

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

我想从 Controller 设置 user_role 。例如:
$scope.user_role = 1

最佳答案

您可以将函数传递给 templateUrl 选项并返回一个字符串,该字符串将在末尾用作模板 url。

首先,将 Angular 色作为属性(其中 userRole 绑定(bind)到范围)分配给元素,如下所示:

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

然后该指令可以将其读取为:
myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
    templateUrl: function(element, attrs) {
      return "../assets/common/headerMenu" + attrs.userRole + ".html";
    }
  }
});

更新:
这曾经适用于旧版本的 Angular。
<div ng-if="userRole === 'admin'" my-directive user-role="admin"></div>

关于angularjs指令动态设置模板url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26397424/

相关文章:

javascript - 如何使用 AngularJS 返回 HTML 页面

javascript - Select 上的 ng-pattern 变小

html - 在自动对焦html5输入日期字段上打开日期选择器AngularJS

angularjs - AngularJS指令隔离范围声明中 '=?'的含义是什么?

javascript - 在加载指令模板之前指令的范围未初始化,导致无法加载 Google map

angularjs - 如何在没有 $rootScope 的情况下切换 Angularjs ng-show

javascript - Angular/Javascript 'rounding' 长值?

angularjs - Webpack FOSJsRoutingBundle 与 Symfony Flex 和 Angular 的集成

Angularjs 列表/详细信息编辑

javascript - 当它更改为不同的网站时,Angular 会观察 url