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

DRYing up your controllers


When defining the model data and methods in controllers, you will quickly become tired of typing $scope repeatedly. Some developers simply take this on the chin and accept it as a necessity of the framework, but there is a superb method that avoids this verbosity and simultaneously makes your controllers more DRY.

Getting ready

Suppose that you have a controller in a fantasy football application, appearing as follows:

app.module('myApp', [])
.controller('Ctrl' function($scope) {
  $scope.team = {
    name: 'Bears',
    city: 'Chicago'
  };
  $scope.player = {
    name: 'Jake Hsu',
    team: 'Bears',
    number: 29,
    position:'RB'
  };
  $scope.trade = function(player1, player2) {
    // $scope.trade() logic
  };
  $scope.drop = function(player) {
    // $scope.drop() logic
  };
});

How to do it…

Even with two scope objects and two methods, the number of times $scope needs to be typed here is extremely annoying. The central reason that demands this verbose syntax...