angularjs指令动态设置模板url

Sac*_*sad 12 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  
Run Code Online (Sandbox Code Playgroud)

我想从控制器设置user_role.例如:

$scope.user_role = 1
Run Code Online (Sandbox Code Playgroud)

cod*_*mer 13

您可以将函数传递给templateUrl选项,并返回一个字符串,该字符串最后将用作模板URL.

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

<div my-directive user-role="{{userRole}}></div>
Run Code Online (Sandbox Code Playgroud)

然后该指令可以将其读作:

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

更新: 以前使用旧版Angular时工作.

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

  • 这实际上不起作用; attrs.userRole直接在"{{userRole}}"字符串中传递,而不是实际值. (16认同)

Jos*_*ush 8

你可以操作ng-include模板

HTML:

<headermenu user-role="selectedUserRole"></headermenu>
Run Code Online (Sandbox Code Playgroud)

JS:

app.directive('headermenu', function() {
  return {
    restrict: 'E',
    scope: {
      userRole : '='
    },
    link: function($scope)
    {
      $scope.$watch('userRole', function(userRole)
      {
        if (userRole && userRole.length)
        {
            $scope.dynamicTemplateUrl = 'assets/common/headerMenu' + userRole + '.html';
        }
      });
    },

    template: '<ng-include src="dynamicTemplateUrl"></ng-include>'
  };
});
Run Code Online (Sandbox Code Playgroud)

演示:http://plnkr.co/edit/CCElZ317kYeZpa5ofmoo?p=preview


或者,如果您不想在控制器中设置完整路径:

HTML:

<headermenu path="assets/common/headerMenu{{selectedUserRole}}.html"></headermenu>
Run Code Online (Sandbox Code Playgroud)

JS:

app.directive('headermenu', function() {
  return {
    restrict: 'E',
    scope: {
      path : '@'
    },
    template: '<ng-include src="path"></ng-include>'
  };
});
Run Code Online (Sandbox Code Playgroud)

演示:http://plnkr.co/edit/HEyUUzv6jbjZCDDbAzPm?p=preview