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

The "Controller as" syntax


AngularJS 1.2 introduced the ability to namespace your controller methods using the "controller as" syntax. This allows you to abstract $scope in controllers and provide more contextual information in the template.

Getting ready

Suppose you had a simple application set up as follows:

(index.html)

<div ng-app="myApp">
  <div ng-controller="Ctrl">
    {{ data }}
  </div>
</div>

(app.js)

angular.module('myApp', [])
.controller('Ctrl', function($scope) {
  $scope.data = "This is string data";
});

How to do it…

The simplest way to take advantage of the "controller as" syntax is inside the ng-controller directive in a template. This allows you to namespace pieces of data in the view, which should feel good to you as more declarative views are the AngularJS way. The initial example can be refactored to appear as follows:

(index.html)

<div ng-app="myApp">
  <div ng-controller="Ctrl as MyCtrl">
    {{ MyCtrl.data }}
  </div>
<...