1

i am trying to find out when and how to use the link function in angular directives.

Say i have the following directive:

    app.directive("lbArticle", function() {
    return {
        restrict : "E",
        templateUrl: 'tpl/directives/information/article.html',
        scope: {
            article: '='
        },
        link: function(scope,element, attr){
            scope.info = attr.article;
        }
    };
});

Now passing an object to the article attachment of the HTML

<lb-article article='{{myObject}}'> </lb-article>

When this happens and the directive is rendered it should set a variable called info equal to myObject

So if myObject looked like this:

myObject{name: 'Hello', created: '2015-04-04'; }

Then the following should display these variables:

my directive html

   <span class="block text-ellipsis">{{info.name}}</span>
    <small class="text-muted">{{info.created | fromNow}}</small>

However this does not work?

As far as i can read for the documentation the link function should be used for DOM manipulation and also for setting variables that might be rendered before the actual directive?

2
  • Also, this line scope.info = attr.article; has no real use, as you already have article in that scope Commented Jun 10, 2015 at 12:04
  • Why do you use link in this example? the scope : {...} already makes article available to the template Commented Jun 10, 2015 at 12:09

2 Answers 2

2

This line scope.info = attr.article; is redundant, since you have access to article via the two-way binding =article. So you can replace all occurrences of info with article in the template, since that is available in scope. You also need to remove the curly brackets from <lb-article article='{{myObject}}'> </lb-article> for two-way binding to work, since you want a reference to the object.

There's a nice, easy to follow article on directives, which covers most of these concepts (link/complile functions, two/one-way binding, scopes, etc.).

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

Comments

0

Use

<lb-article article='myObject'> </lb-article>

and try now.

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.