我正在使用模板 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/