6

Look at example:

$scope.fields = [{
    name: 'Email',
    dir : "abc"
}, {
    name: 'List',
   dir : "ddd"
}];

app.directive('abc', function () {});
app.directive('ddd', function () {});

<table class="table table-hover">
        <tr ng-repeat="p in fields">
          <input {{p.dir}} ngmodel="p" />
        </tr>
    </table>

How can I write code, that p.dir will dynamically convert to a directive ?

My example: hhttp://jsbin.com/vejib/1/edit

3
  • Do you really need a directive for this? Can you just change to <td>dddd: {{p.name}}</td><td>ddd: {{p.age}}</td>? Commented Apr 17, 2014 at 10:41
  • @RuslanIsmagilov It's not about visual. Eash directive has it's own business logic. I'd like to dynamically build forms with custom business logic. Commented Apr 17, 2014 at 10:45
  • I think I have had similar porblems you need to set the directive scope to isolate. check the docs docs.angularjs.org/guide/directive Commented Apr 17, 2014 at 11:13

2 Answers 2

10

Try this directive:

app.directive('dynamicDirective',function($compile){
  return {
      restrict: 'A',
      replace: false, 
      terminal: true, 
      priority: 1000, 
      link:function(scope,element,attrs){

        element.attr(scope.$eval(attrs.dynamicDirective),"");//add dynamic directive

        element.removeAttr("dynamic-directive"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-dynamic-directive");

        $compile(element)(scope);
      }
  };
});

Use it:

<table class="table table-hover">
   <tr ng-repeat="p in people">
      <td dynamic-directive="p.dir" blah="p"></td>
   </tr>
</table>

DEMO

For more information on how this directive works and why we have to add terminal:true and priority: 1000. Check out Add directives from directive in AngularJS

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I thought angular has something like that build-in. apparently not.
0

You could put this:

<input {{p.dir}} ngmodel="p" />

also in a directive. You could construct this HTML string in JavaScript and attach it to the DOM. And you would also need to compile the resulting element using the $compile service, so that the dynamic directives will be compiled.

Some dummy sample code (not tested, but should look something like this):

app.directive('dynamicInput', function($compile){
return {
    link: function(scope, element){
        var htmlString = '<input ' + scope.field.dir + ' ng-model="p"/>';
        element.replaceWith(htmlString);
        $compile(angular.element(element))(scope);
    }
}

});

More info here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.