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?

2
  • possible duplicate of Angular.js directive dynamic templateURL Commented Aug 2, 2015 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 Commented Aug 2, 2015 at 13:42

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

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.