2

I want to build a custom directive where I can pass an object and depending on that object render a different HTML.

Let's say that the object look's like this.

$scope.obj = {
  type: 'input',
  placeholder: 'Some text…',
  name: 'first_name'
}

The custom directive should look like this (I guess)

<renderObj data="obj" />

This should render a input field with the given data. I guess I have to use either the link or compile method within the directive, but how? Notice that the obj could have many different types of data and would be more complex than this simple example. So I must be able to decide within the directive what to render with which data.

Maybe I don't need a custom directive at all and use ng-include instead?

YeppThat'sMe
  • 1,812
  • 6
  • 29
  • 45
  • possible duplicate of [Angular.js directive dynamic templateURL](http://stackoverflow.com/questions/21835471/angular-js-directive-dynamic-templateurl) – callmekatootie Aug 02 '15 at 11:48
  • There are lots of ways to include display logic within directives. Try something and when it isn't working as expected post that code – charlietfl Aug 02 '15 at 13:42

1 Answers1

1

You could use $compile to build out dynamic DOM. Code within the directive would look like this:

link: function (scope, element) {
  // ...
  if (data.type === 'input') {
    $compile('<input type="text" placeholder="{{placeholder}} name="{{name}}"></input>')(scope.data, function (clonedElement) {
      element.append(clonedElement);
    });
  }
  // ...

Generally though I would suggest trying to do as much of this in your directive template as possible. Imagine a template for the directive like:

<div>
  <input ng-if="data.type == 'input'" type="text" placeholder="{{data.placeholder}}" name="{{data.name}}" />
</div>
Zachary Kuhn
  • 1,152
  • 6
  • 13