Pro AngularJS

Models—the M in MVC—contain the data that users work with.
There are two broad types of model: view models, which represent just data passed from the controller to the view, and domain models, which contain the data in a business domain, along with the operations, transformations, and rules for creating, storing, and manipulating that data, collectively referred to as the model logic.

For each component in the MVC pattern, I’ll describe what should and should not be included. The model in an
application built using the MVC pattern should
Contain the domain data
Contain the logic for creating, managing, and modifying the domain data (even if that means executing remote logic via web services)
Provide a clean API that exposes the model data and operations on it The model should not
Expose details of how the model data is obtained or managed (in other words, details of the data storage mechanism or the remote web service should not be exposed to controllers and views)
Contain logic that transforms the model based on user interaction (because this is the controller’s job)
Contain logic for displaying data to the user (this is the view’s job)

Controllers are the connective tissue in an AngularJS web app, acting as conduits between the data model and views.
Controllers add business domain logic (known as behaviors) to scopes, which are subsets of the model.

A controller built using the MVC should
Contain the logic required to initialize the scope
Contain the logic/behaviors required by the view to present data from the scope
Contain the logic/behaviors required to update the scope based on user interaction
The controller should not
Contain logic that manipulates the DOM (that is the job of the view)
Contain logic that manages the persistence of data (that is the job of the model)
Manipulate data outside of the scope

The domain model isn’t the only data in an AngularJS application.

Controllers can create view data (also known as view model data or view models) to simplify the definition of views.

View data is not persistent and is created either by synthesizing some aspect of the domain model data or in response to user interaction.

Views should
Contain the logic and markup required to present data to the user Views should not
Contain complex logic (this is better placed in a controller)
Contain logic that creates, stores, or manipulates the domain model
Views can contain logic, but it should be simple and used sparingly. Putting anything but the simplest method
calls or expressions in a view makes the overall application harder to test and maintain.

Filter - Chapter 14

ng-class - Chapter 11

AngularJS tries to prevent tightly coupled components - Chapter 3.

$filter - Chapter 14

Services - Chapter 3

$http - Chapter 23

jQuery - Chapter 5, Chapter 20

JSON - Chapter 5

built-in directives - Chapter 9-12

Directives use jaLite - Chapter 15

Directives - Chapter 16

When AngularJS encounterrs the ng-include directive,

it makes an Ajax request, loads the file specified by the src attribute,

and inserts the contents in place of the element.

Services - Chapter 18

Directives are created by calling the directive method on an AngularJS module and passing in the name of the directive (cartSumary in this case)

angular.module("cart", [])
.directive("cartSummary", function (cart) { ... }

and a factory function that returns a directive definition object.

return {
restrict: "E",
templateUrl: "components/cart/cartSummary.html",
controller: function ($scope) {
var cartData = cart.getProducts();
$scope.total = function () {
var total = 0;
for (var i = 0; i < cartData.length; i++) {
total += (cartData[i].price * cartData[i].count);
}
return total;
}
$scope.itemCount = function () {
var total = 0;
for (var i = 0; i < cartData.length; i++) {
total += cartData[i].count;
}
return total;
}
}
};

Complete set of Directive properties in Chapters 16 and 17.

Name Description
restrict Sepcifies how the directive can be applied. I have used a value of E, which means that this directive can be applied only as an element. The most common value is EA, which means that the directive can be applied as an element or as an attribute.
templateUrl Specifies the URL of a partial view whose contents will be inserted in to the directive’s element.
controller Specifies a controller that will provide data and behaviors to the partial view.

AngularJS normalizes component names - Chapter 15.

URL routing - Chapter 22.

URl routing - it allows for different partial views to be displayed automatically based on the current URL.

ngRoute - angularjs-route.js

Call config method on the module object.

The config method takes a function as its argument, which is executed when the module is loaded but before the application is executed, providing an opportunity for any one-off configuration tasks.

angular.module("sportsStore", ["customFilters", "cart", "ngRoute"]) 
.config(function ($routeProvider) {} )

The function that I passed to the config method declares a dependency on a provider.

One of creating a service is that can be configured through a provider object, whose name is the concatenation of the service name and Provider.One

The $routeProvider that I have declared a dependency on is the provider for the $route service and is used to set up the URL routing in an application.

Create services with providers — Chapter 18

$route and $routeProvider — Chapter 22

*when

$routeProvider.when("/checkout", { ... });

*otherwise

$routeProvider.otherwise({ ... });

novalidate

disable any validation that the browser might try to perform.

URL routing feature to prevent AngularJS from displaying the view until the Ajax request has been completed. - Chapter 22

Use promises to build chains of behavior - Chapter 20

$animate - Chapter 23

complete set of configuration options use URL routes - Chapter 22

$http.post - Chapter 20

*$location - Chapter 11

$http - Chapter 20

how services work - Chapter 18

Scopes - Chapter 13

Understanding Dependency Injection

Using the Form Directive Attributes

Input

** Only works when the input element does not have a type attribute or when the type attribute is
text, url, email, or number.

name Description
ng-model Specifies a two-model binding, as descibed earlier in this chapter
ng-change Specifies an expression that is evaluated when the contents of the element are changed
ng-minlength Sets a minimum number of characters required for the element to be valid
ng-maxlength Sets a maximum number of characters required for the element to be valid
ng-pattern Sets a regular expression. The contents of the element must match this pattern in order to be valid
ng-required Sets the value of the required attribute with a data binding

Checkbox

The Attributes That Can Be Used for an input Element Whose type Attribute Is checkbox

Name Description
ng-model Specifies a two-model binding, as described earlier in this chapter
ng-change Specifies an expression that is evaluated when the contents of the element are changed
ng-true-value Specifies the value that the model binding expression will be set to when the element is checked
ng-false-value Specifies the value

Text Areas

name Description
ng-model Specifies a two-model binding, as descibed earlier in this chapter
ng-change Specifies an expression that is evaluated when the contents of the element are changed
ng-minlength Sets a minimum number of characters required for the element to be valid
ng-maxlength Sets a maximum number of characters required for the element to be valid
ng-pattern Sets a regular expression. The contents of the element must match this pattern in order to be valid
ng-required Sets the value of the required attribute with a data binding

Select

name Description
ng-options
ng-required

ng-options="item.action for item in todos"

<select ng-model="selectValue" ng-options="item.action for item in todos">
<option value="">(Pick One)</option>
</select>
<select ng-model="selectValue" ng-options="item.id as item.action for item in todos">
<option value="">(Pick One)</option>
</select>
ng-options="item.action group by item.place for item in todos">
ng-options="item.id as item.action group by item.place for item in todos">

Using the Services Method

var baseLogger = function () {

this.messageCount = 0;

this.log = function (msg) {
console.log(this.msgType + ": " + (this.messageCount++) + " " + msg);
}
};

var debugLogger = function () { };

debugLogger.prototype = new baseLogger();

debugLogger.prototype.msgType = "Debug";

var errorLogger = function () { };

errorLogger.prototype = new baseLogger();

errorLogger.prototype.msgType = "Error";

angular.module("customServices", [])
.service("logService", debugLogger)
.service("errorService", errorLogger);

Using Factory Method

angular.module("customServices", [])
.factory("logService", function () {
var messageCount = 0;
return {
log: function (msg) {
console.log("(LOG + " + messageCount++ + ") " + msg);
}
};
});
angular.module("customServices", [])
.provider("logService", function(){
return {
$get: function() {
return {
messageCount: 0,
log: function(msg) {
console.log("(LOG + " + this.messageCount++ + ") " + msg);
}
};
}
};
});

Table 9-3. The Members of the Module Object

Name Description
animation(name, factory) Supports the animation feature, which I describe in Chapter 23.
config(callback) Registers a function that can be used to configure a module when it is loaded. See the “Working with the Module Life Cycle” section for details.
constant(key, value) Defines a service that returns a constant value. See the “Working with the Module Life Cycle” section later in this chapter.
controller(name, constructor) Creates a controller. See Chapter 13 for details.
directive(name, factory) Creates a directive, which extends the standard HTML vocabulary. See Chapters 15–17.
factory(name, provider) Creates a service. See Chapter 18 for details and an explanation of how this method differs from the provider and service methods.
filter(name, factory) Creates a filter that formats data for display to the user. See Chapter 14 for details.
provider(name, type) Creates a service. See Chapter 18 for details and an explaination of how this method differs from the service and factory methods.
name Returns the name of the module.
run(callback) Registers a function that is invoked after AngularJS has loaded and configured all of the modules. See the “Working with the Module Life Cycle” section for details.
service(name, constructor) Creates a service. See Chapter 18 for details and an explanation of how this method differs from the provider and factory methods.
value(name, value) Defines a service that returns a constant value; see the “Defining Values” section later in this chapter.

List:

Problem Solution Listing
Define a service. Use the Module.service, Module.factory, or Module.provider method. 12
Define a service from an existing object or value. Use the Module.value method. 13
Add structure to the code in an application. Create multiple modules and declare dependencies from the module referenced by the ng-app attribute. 14–16
Register functions that are called when modules are loaded. Use the Module.config and Module.run methods. 17
angular.module("customServices", [])
.provider("logService", function(){
return {
$get: function() {
return {
messageCount: 0,
log: function(msg) {
console.log("(LOG + " + this.messageCount++ + ") " + msg);
}
};
}
};
});