问题
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