angularjs directive set template url dynamically

后端 未结 4 2141
刺人心
刺人心 2021-02-19 22:19

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.d         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 22:53

    you can manipulate ng-include as a template

    html:

    
    

    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: ''
      };
    });
    

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


    Or if you don't want to set the full path in the controller:

    html:

    
    

    js:

    app.directive('headermenu', function() {
      return {
        restrict: 'E',
        scope: {
          path : '@'
        },
        template: ''
      };
    });
    

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

提交回复
热议问题