Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - How to pass custom directive name dynamically in class attribute of div tag?

I am very new to AngularJS. I have made a custom directive user and I want to call it dynamically in class attribute by using a variable. e.g. $scope.dirName = "user"; When i use this variable in below code:

<div class = {{dirName}}></div>

Its result must show two input fields with specified values. But it is not doing so. When I replace {{dirName}} with user. It is working fine, means two input fields are shown with values as specified. Can anybody tell, what mistake I am doing?

This is index.html

<div ng-controller = "Ctrl">
<form name = "myForm">
  <div class = {{dirName}}></div>
  <hr>
  <tt>userName : {{user}}</tt>
</form>

This is script.js

<pre>var app = angular.module('App',[]);

app.controller('Ctrl', function($scope){
 $scope.user = {name:'adya',last:'Rajput'};
 $scope.dirName = "user";
});

app.directive('user',function(){
 return{
   restrict:'C',
   templateUrl:'template.html'
 };
});</pre>

template.html contains:

UserName : <input type='text' name='userName' ng-model='user.name' required>
LastName : <input type='text' name='lastName' ng-model='user.last'>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, you cannot save names of directives in string variables and access them in the HTML. You can, however, save a string in a variable in $scope and use ng-switch to select the correct directive:

<div ng-switch="dirName">
    <div ng-switch-when="ng-user">
      <div ng-user></div>
    </div>

    <div ng-switch-when="...">
      ...
    </div>
</div>

However, now it might be better to use something more descriptive than ng-user to switch over.

Sidenote: Do not use ng- prefix in your own directives. Angular uses that prefix so that it does not collide with other namespaces. You should use your own prefix for your directives.


Update: For the updated question as to why <div class="{{dirName}}"></div> does not work, it happens because angular $compiles the directive only once. If you first $interpolate the content of the template (which will replace {{dirName}} with ng-user) and then explicitly $compile it before entering it in the HTML, it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...