0

I'm trying to build a simple directive that creates a link on the page to google with dynamic values via the '@' binding strategy, I have it working, but I'm not sure what '@' is doing.

My directive looks like this:

(function() {
var app = angular.module('app', []);

app.directive('myDirective', function() {
    return {
        restrict: 'A',
        replace: true.
        scope: {
            myUrl: '@', // binding
            myLinkText: '@'
        },
        template: '<a href="{{myUrl}}">{{myLinkText}}</a>'
    }
});

})();

And here's my HTML:

<div my-directive
    my-url="http://google.com"
    my-link-text="Click me to go to Google.">
</div>

How is this different from creating a controller and why do we need to do this in directives? In other words, why do we need to create another scope? I'm not understanding the concept of isolate scope and binding. Thanks for your help.

1 Answer 1

2

By default, your directive uses scope inheritance. This means that if a scope variable is not defined in the current scope, it will search for the variable in the parent scope, and then its parent scope, until finally, it stops searching at the $rootScope. Isolating your scope does not allow scope inheritance - it is a way to make your directive more self contained, and more modular with fewer dependencies. The most common way that variables from your outside scope are imported to your isolated scope is through the attributes. This is where the @ comes into play. There three ways to import a scope variable:

  1. @ - As a string (which may be interpolated).
  2. = - With two-way binding to a model object.
  3. & - As an expression that is evaluated in parent scope (mainly for method calls that evaluated in parent scope).
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.