How to dynamically add a custom directive to a div element?

假装没事ソ 提交于 2019-12-22 08:31:16

问题


I'm a beginner at angularjs, please take it easy on me. So I have this directive and would like to dynamically append it to a div element. How should I do it?

appDirectives.directive('test', function () {
    return  {
        restrict: 'E',
        templateUrl: 'templates/test.html'
    }
});

I tried this but it didn't work. I'm assuming the template didn't get compiled before I appended to the div element. Is there an angular way to do this?

<div id="element"></div>

$('#element').append(<test></test>);

Update: Here is what I'm trying to do. When a user logged in my page, I have 3 different templates that I would like it to show up depend on the type of of user. The 3 templates are <basic>, <regular>, <advance> Basically after user logged in, I would have the value of a variable user.type and would like to show the appropriate template for that user.

Any suggestions would help. Thank you :)


回答1:


Something like this, may be? http://plnkr.co/edit/SmL9fA5GzAxI2WYTnYZy

Angular way is to represent the view by javascript object (in the scope) and let Angular templating system to refrect your model.




回答2:


ng-switch is probably what you want:

<div id="element" ng-switch on="user.type">
  <span ng-switch-when="basic"><basic></basic></span>
  <span ng-switch-when="regular"><regular></regular></span>
  <span ng-switch-when="advance"><advance></advance></span>
</div>

Plunker



来源:https://stackoverflow.com/questions/16184557/how-to-dynamically-add-a-custom-directive-to-a-div-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!