1

I am adding the following div multiple times on a page.

<div class="box span6">
    <div class="box-header">
        <h2 class="custom"><i class="fa-icon-group" style="opacity:.7"></i><span class="break"></span>[TEXT]</h2>
    </div>
    <div class="box-content">
        <p><strong>[TEXT 2]</strong></p>
        <ul>
            <li ng-repeat = "course in courses">{{course}}</li>
        </ul>
    </div>
</div>

I'd like to write a directive but I don't know how to pass values to the directive.

Eg. I want to pass "name" for TEXT and "email address" for "Text 2" and list of books for "courses".

Is there any way to pass values to directive like passing values to a function?

2 Answers 2

1

Arguments to a function are like HTML attributes to a directive. In your link and compile functions, you get an attributes object, which contains the normalised names and values of all the attributes on the element.

For example, you could have <div data-awesome-directive data-color="red" data-size="16"></div>. The directive's link function could look like link: function (scope, element, attributes) { ... }. In there, you can access the values of the attributes as properties of the object: attributes.awesomeDirective, attributes.color, and attributes.size. Notice how the names are normalised (awesome-directive becomes awesomeDirective).

For more advanced things, such as function calls or expressions, look into $parse. It can parse an expression such as foo.bar() and call it on a scope.

HTH!

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

Comments

0

To add on to stevuu's response, if you wanted to pass values to the directive that are variables in the scope you can do so as follows:

<div data-awesome-directive data-color="selected_color" ... ></div>

where selected_color is set in the containing scope. In the link function, the color can be obtained and set in the directive's scope via:

link: function(scope, element, attributes) {
  scope.color = scope.$eval(attributes.color);
}

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.