AngularJS directives: link function and scope isolation “&”

This snippets shows you a simple use of the link function and of scope isolation “&”.
Our goal is the creation of a reusable tabbar directive in AngularJS that notify the controller each time a menu item is clicked.

Result (click on menu items):

index.html

app.js

controller.js

Notes about “controller as” syntax

  • This syntax makes it clear where a property comes from, especially when using nested controllers
  • You can use this instead of $scope inside your controller
  • You can avoid some of the dot rule problems (when binding primitives)

directive.js

The link function

Some notes about the link function:

  • By default a directive does not get a new child scope. Rather, it gets the parent’s scope.
    Using the scope isolation our directive will have its own scope and the place where we can use our scope properties or where manipulate the scope is a function called link function.
  • the link function has the following signature: link(scope, element, attrs): in this tutorial we only use the scope property in order to create a function you can call from the directive template and to call the controller method using the scope isolation “&”

templates/tabbar.tpl.html

VIDEO TUTORIAL (Italian only)

The following step-by-step tutorial (italian only) describes all the concepts of the snippet above:


Fabio Biondi

I am an italian developer with over 10+ years of experience in developing custom user interfaces and interactive applications for any screen and device using the latest web technologies - HTML5, SVG, Canvas, ES2015, CSS3 - the latest libraries - React, AngularJS, D3.js, CreateJS - and many other tools - Gulp, WebPack, LESS/SASS but also Sketch, Balsamiq, PS and AI.