Book Image

AngularJS Web application development Cookbook

By : Matthew Frisbie
Book Image

AngularJS Web application development Cookbook

By: Matthew Frisbie

Overview of this book

Packed with easy-to-follow recipes, this practical guide will show you how to unleash the full might of the AngularJS framework. Skip straight to practical solutions and quick, functional answers to your problems without hand-holding or slogging through the basics. Avoid antipatterns and pitfalls, and squeeze the maximum amount out of the most powerful parts of the framework, from creating promise-driven applications to building an extensible event bus. Throughout, take advantage of a clear problem-solving approach that offers code samples and explanations of components you should be using in your production applications.
Table of Contents (17 chapters)
AngularJS Web Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Isolate scope


Often, you will find that the inheritance of a directive's parent scope is undesirable somewhere in your application. To prevent inheritance and to create a blank slate scope for the directive, isolate scope is utilized.

Getting ready

Suppose that you begin with the following skeleton application:

(index.html - uncompiled)

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <my-directive>
      Stuff inside
    </my-directive>
  </div>
  
  <script type="text/ng-template" id="my-directive.html">
    <div>
      <p>Directive template</p>
      <p>Scope from {{origin}}</p>
      <p>Overwritten? {{overwrite}}</p>
    </div>
  </script>
</div>

(app.js)

angular.module('myApp', [])
.controller('MainCtrl', function ($scope) {
  $scope.overwrite = false;
  $scope.origin = 'parent controller';
});

How to do it…

Assign an isolate scope to the directive with an empty object literal, as follows:

(app.js)

.directive('myDirective', function() {
  return {
    templateUrl: 'my-directive.html',
    replace: true,
    scope: {},
    link: function (scope) {
      scope.overwrite = !!scope.origin;
      scope.origin = 'link function';
    }
  };
});

This will compile into the following:

(index.html – compiled)

<div>
  <p>Directive template</p>
  <p>Scope from link function</p>
  <p>Overwritten? false</p>
</div>

How it works…

The directive creates its own scope and performs the modifications on the scope instead of performing them inside the link function. The parent scope is unchanged and obscured from inside the directive's link function.

See also

  • The Directive scope inheritance recipe goes over the basics that involve carrying the parent scope through a directive

  • The Directive templating recipe examines how a directive can apply an external scope to an interpolated template

  • The Directive transclusion recipe demonstrates how a directive handles the application of a scope to the interpolated existing nested content