angularjs 指令动态设置模板 url [英] angularjs directive set template url dynamically
问题描述
我正在创建一个带有模板 URL 的指令.我想根据 user_role 动态设置模板 URL.有什么想法吗?
I'm creating a directive with template URL. I want to set the template URL dynamically based on user_role. Any idea?
这是我的指令代码:
RatingRX.directive "headermenu", ->
directive = {}
directive.restrict = 'E'
directive.templateUrl = "../assets/common/headerMenu{{user_role}}.html"
directive
我想从控制器设置 user_role.例如:
And I want to set user_role from the controller. Eg:
$scope.user_role = 1
推荐答案
您可以将一个函数传递给 templateUrl 选项并返回一个字符串,该字符串将在最后用作模板 url.
You can pass a function to the templateUrl option and return a string that will be used as a template url at the end.
首先将角色作为属性分配给元素(其中 userRole 绑定到作用域)为:
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";
}
}
});
更新:这曾经适用于旧版本的 Angular.
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屋!