This is an unofficial free book created for educational purposes and is not affiliated with the official AngularJS group(s) or company(s) or Stack Overflow. The information presented in this book is not guaranteed to be correct or accurate, use at your own risk.
Getting started with AngularJS
Getting Started
If you use control bars you can see the actual Hello, {{name}} as the page loads before the expression is resolved (before the data is loaded) while if you use ng-bind it will display the data only when the name is resolved.
Showcasing all common Angular constructs
As an alternative, the ng-cloak directive can be used to prevent the helm from being displayed before it is compiled.
The importance of scope
Of course, most of the time we create a controller and inject the required functionality into that controller. However, it is important to note that even with the As controller syntax, there is a local scope.
Minification in Angular
AngularJS Getting Started Video Tutorials
The Simplest Possible Angular Hello World
We tell Angular which part of our DOM to treat as the main template using the ng-app directive. We can also write our own guidelines, and these will be treated the same as the built-in guidelines.
Modules
Modules
Modules
Run Blocks: run after the injector is created and used to start the application. here you can only inject instances into configuration blocks.
Components
Basic Components and LifeCycle Hooks
Parameters passed to the component are available in the controller's scope just before its $onInit function is called by Angular.
Components In angular JS
Built-in directives
Angular expressions - Text vs. Number
To repeat multiple DOM elements by defining a start and end point, you can use the ng-repeat-start and ng-repeat-end directives. To access the index of the parent ng-repeat within the child ng-repeat, you can use $parent.$index.
Built-In Directives Cheat Sheet
The example above adds a 500 millisecond debounce effect to myValue, which updates the model 500 ms after the user finishes typing the input (that is, when the myValue finishes updating).
By default, ng-list does not consider whitespace unless you set ng-trim="false". And the model of the input box is set to the array created on the scope.
You can set the limit manually by assigning ng-list a delimeter like this ng-list. There is no visual difference when using trackBy, but Angular will detect changes by id instead of reference which is always a better solution.
The ng model variable in this case will be available in your controller as $scope.myName. This way you don't have to inject $scope into your controller to reference your ng model variable; the variable will be available as this.myName in your controller's function.
As you type in the input field or change it in any way, you will immediately see the updated value in the paragraph. You will need to refer to the controller scope by pre-adding the controller alias defined in the ng-controller attribute to the ng-model variable.
In the example above, the value stored in the input will be incremented when the button is double-clicked.
Use of in-built directives
Hide/Show HTML Elements
Custom Directives
Below you will find information about what directives are, as well as basic and advanced examples of how to use them.
Creating and consuming custom directives
Directive Definition Object Template
How to create resuable component using directive
New directives can simply be added inside reusableModuleApp.js and reusableModuleApp can have its own controller, services, DDO object inside the directive to define the behavior.
Basic Directive example
Directive decorator
The directive is called myDirective, so you need to configure myDirectiveDirective. this in an angular convention [read about providers]. This example adds an onClick event to the directive element when it is clicked, this happens during the compile phase.
Basic directive with template and an isolated scope
Building a reusable component
Directive inheritance and interoperability
How data binding works
Data Binding Example
For in-depth object validation, the object // value-based validation code should be implemented here watcher.last = newValue;. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside a handler function, you must call $apply() to ensure that the changes take effect.
Angular Project - Directory Structure
Directory Structure
All the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and so on.
Filters
Accessing a filtered list from outside an ng-repeat
Custom filter to remove values
Custom filter to format values
Using filters in a controller or service
Performing filter in a child array
Custom filters
Use a filter in a controller, a service or a filter
Create a filter with parameters
Simple filter example
In this case, the variable we defined in the controller, sample, is being filtered by the filter we created, addZ.
Constants
Create your first constant
Use cases
Custom filters with ES6
FileSize Filter using ES6
Directives using ngModelController
A simple control: rating
Control can of course be parameterized; use '= 1.5 to 3. If you need to take action every time a parameter changes, you can use a JavaScript property (see Object.defineProperty()) to store some views.
A couple of complex controls: edit a full object
Additionally, we rebuild the watch (this_unwatch(); this._makeWatch();), to avoid prompting the watcher for changes pushed to us by the model. We just want the watch to trigger the changes made to the UI.). In addition to the above points, we implement ngModel.$render() and call ngModel.$setViewValue() as in 3.
Controllers
Your First Controller
Note that the name we pass here is the same as the name you set in your HTML with the ng-app directive. Note: For anything we want to be part of the controller instance, we use the this keyword.
Creating Controllers, Minification safe
Note: Angular uses two-way data binding, which means that no matter how you update the mc.title value, it will be reflected in both the controller and the page. When injecting dependencies using the array form, make sure that the list of dependencies matches the corresponding list of arguments passed to the controller function.
Using ControllerAs in Angular JS
Intentional Bug: Injected dependencies are reversed, which will cause a problem app.controller('sampleController', ['$scope', '$http',function($http, $scope) { $http.get('sample.json' );. It promotes the use of binding to a "dotted" object in the view (eg customer.name instead of name), which is more contextual, easier to read, and avoids reference problems that can occur without "dots ".
Creating Minification-Safe Angular Controllers
NOTE: using the controllerA syntax adds the current scope reference to the current controller so that it is available as a field.
Creating Controllers
Nested Controllers
Controllers with ES6
Controller
The Self Or This Variable In A Controller
Understanding The Purpose Of The Self Variable
That's the beauty of using the "self" variable in your controllers - you can access it anywhere in your controller and you can always be sure it's referring to your controller instance.
Services
Creating a service using angular.factory
Dierence between Service and Factory
But if you don't want to use a constructor and instead use a simple API pattern, then there isn't much flexibility in .service(). 2) Factory. Let's see an example where factory is used to return an object using a standard Revealing module pattern function StudentDetailsService($http).
How to create a Service
How to use a service
How to create a Service with dependencies using 'array syntax'
Registering a Service
Distinguishing Service vs Factory
Factory VS Service once-and-for-all
Angular promises with $q service
Wrap simple value into a promise using $q.when()
Using angular promises with $q service
The purpose of a promise object is to allow interested parties to access the result of a deferred task when it has completed. In addition, the notification callback may be called zero or more times to provide an indication of progress before the promise is resolved or rejected.
Using the $q constructor to create promises
The constructor function takes a function that is called with two arguments, resolve and reject which are functions used to resolve or reject the promise. The above code showing a promise division function, it will return a promise with the result or reject it with a reason if the computation is impossible.
Avoid the $q Deferred Anti-Pattern
There is no need to make a promise with $q.defer, because the $http service already returns a promise.
Using $q.all to handle multiple promises
Deferring operations using $q.defer
Dependency Injection
Dynamic Injections
Dynamically load AngularJS service in vanilla JavaScript
Events
Using angular event system
The reason for cleaning the registered events is because even the controller has been destroyed, the handling of the registered event is still alive.
Always deregister $rootScope.$on listeners on the scope $destory event
Uses and significance
Sharing Data
Using ngStorage to share data
Sharing data from one controller to another using service
Here we can see that myCtrl1 is used to set the data and myCtrl2 is used to get the data.
Form Validation
Form and Input States
CSS Classes
Basic Form Validation
The ng-model directive provides two-way binding with input fields, and usually the novalidate attribute is also placed on the form element to prevent the browser from performing native validation. This is not mandatory, but it is usually used since the input variables are already available at scope and therefore available to your submit function.
Custom Form Validation
For Angular to validate input, use exactly the same syntax as a regular input element, except for the addition of the ng-model attribute to specify which variable to bind to on the scope. The final steps for basic form validation is to connect to a form submission function on the controller using ng-submit, instead of allowing the default form submission to occur.
Async validators
The validator is defined as a directive that requires ngModel, so to use the validator you simply add a custom directive to the input form control.
Nested Forms
Routing using ngRoute
Basic example
Defining custom behavior for individual routes
Route parameters example
Three types of ng-class expressions
This creates a text input field bound to the UserStyle scope variable that lets the user type one or more class names. The user can also click the checkbox that is data bound to the alert scope variable.
Iterating over object properties
Tracking and Duplicates
Use of ng-style
Registration navigation
AngularJS bindings options (`=`, `@`, `&` etc.)
Bind optional attribute
Available binding through a simple sample
Providers
Provider
Factory
Constant
Service
The Factory recipe constructs a new service using a function with zero or more arguments (these are dependencies on other services). The constructor can take zero or more arguments, representing the dependencies needed for the instance of this type.
Value
Decorators
Decorate service, factory
Decorate directive
Decorate filter
Print Service
Basic Example
Multiple Views
Using resolve functions to load data
The resolver functions must be resolved before the $stateChangeSuccess event is fired, meaning that the UI will not load until all the resolver functions in the state have completed. But you can see that the resolve function should be fast to avoid UI hang.
Nested Views / States
Built-in helper Functions
This ng iteration binds 5 elements to 5 variables, called number, with a different value for each of them. But as we saw, the context (or scope) of variables within ng-repeat is different from the context above it.
Each scope contains properties, which are the variables bound to the DOM, and the $digest and $watch functions are implemented as methods of the scope. This way - after the input is changed - $digest is called for the div's scope, which then runs the $digest for its 5 children - which will update its contents.
Angular $scopes
A function available in the entire app
Avoid inheriting primitive values
Using only non-primitive values as scope properties will keep you on the safe side (unless you need a property to not inherit, or other cases where you are aware of scope inheritance).
Basic Example of $scope inheritance
How can you limit the scope on a directive and why would you do this?
Guidelines with the new isolated scope: When we create a new isolated scope, it will not be inherited from the parent scope. This new scope is called an Isolated scope because it is completely detached from its parent scope.
Using $scope functions
Of course, you can use ngMouseover for the same thing, but what's special about directives is that you can customize them however you want.
Creating custom $scope events
The above example fires all event listeners for my-event at the parent scope and continues down the scope tree to $rootScope unless a listener calls stopPropagation on the event. The inverse of $emit is $broadcast, which fires event listeners on all child scopes in the scope tree that are children of the scope that called $broadcast.
Using AngularJS with TypeScript
Using Bundling / Minification
Angular Controllers in Typescript
After creating the controller class, make the angular js module about the controller simple by using the class.
Using the Controller with ControllerAs Syntax
Why ControllerAs Syntax?
ControllerAs syntax makes it much clearer where objects are manipulated. With oneCtrl.name and. Hide the $scope and expose the members of the controller to the view via an intermediary object.
Timing of an $http request
Using $http inside a controller
Using $http request in a service
Prepare for Production - Grunt
View preloading
To use this way of concatenation, you need to make 2 changes: In your index.html file, you need to refer to the concatenated view file. In the file, where you declare your application, you should inject the dependency angular.module('app', ['app.templates']).
Script optimisation
If you are using popular routers like ui-router, there is no change in how templates are referenced.
Grunt tasks
Run application locally
To get your application up and running from scratch, store the above files in your project's root directory (any empty folder will do). There is only index.html template, angular code in app.js and few styles in app.css.
Lazy loading
Preparing your project for lazy loading
Usage
Usage with router
Using dependency injection
Using the directive
HTTP Interceptor
Generic httpInterceptor step by step
Getting Started
Flash message on response using http interceptor
Since only providers can be injected in the configure method of an angular module (that is httpProvider and not the rootscope), declare the method attached to rootscope inside the run method of angular module. Try to inject $rootScope or any other services inside the configuration method of angular module, the lifecycle of angular application does not allow it and unknown provider error will be thrown.
Session storage
Handling session storage through service using angularjs
Angular MVC
The Static View with controller
Controller Function Definition
Adding information to the model
SignalR with AngularJS
SignalR and AngularJS [ ChatProject ]
Go to your "/Application/Factories" directory and add the [SignalR-factory.js] file SignalR-factory.js.
Migration to Angular 2+
Converting your AngularJS app into a componend-oriented structure
Notice how we now reference the variable myUserList, which belongs to the controller, using . That's because, as you probably discovered after reading the documentation, $ctrl in the template now points to the controller function.
Introducing Webpack and ES6 modules
Now that you have a component that contains your application (whether it contains the entire application or a part of it, such as a view), you now need to start dividing your component into several nested components, wrapping parts of it in sub-components young people, and so on. After reading the Component documentation, you should already know how to use all those component features, but if you need a concrete example of a real simple application, you can check this out.
AngularJS with data filter, pagination etc
AngularJS display data with filter, pagination
Profiling and Performance
7 Simple Performance Improvements
With more viewers, the summary loop takes longer and the user interface becomes slower. If the observer detects change, the summary loop is started and the display is displayed again.
Bind Once
PROTIP: If you're looking for the best performance approach, go with the $inject property annotation approach. Note: However, this removes the two-way data binding for my.data, so whenever this field changes in your application, the same will not automatically be reflected in the view.
Watchers
If an observer detects changes, it will start the digest loop (recalculation across the screen). You can count watchers with this script (credit @Words Like Jared - How to count total hours on a page.
Always deregister listeners registered on other scopes other than the current scope
If you don't want to create your own script, there's an open source utility called ng-stats that uses a real-time graph embedded in the page to give you insight into the number of watches Angular manages, as well as the .
Scope functions and filters
Debounce Your Model
Not only can you delay in time, but you can also delay when the action is triggered. If you don't want to update your ng model on every keystroke, you can also update it in blur.
Performance Profiling
All About Profiling
With this you can perform a free website speed test from many countries around the globe using real browsers (IE and Chrome) and with real consumer connection speeds. You can run simple tests or run advanced tests including multi-step transactions, video capture, content blocking and much more.
Debugging
Using ng-inspect chrome extension
Application performance can be monitored by counting the number of scopes, isolateScopes, watchers, and listeners on the application.
Getting the Scope of element
Basic debugging in markup
An output of the model in a pre-tag is useful to see the current data for your model. The pre tag is used because inside that tag any newline character \n will be displayed correctly.
Unit tests
Unit test a component (1.5+)
Unit test a filter
Note: In the inject call in the test, your filter must be specified with the name + Filter. The reason for this is that whenever you register a filter for your module, Angular registers it with a filter added to the name.
Unit test a service
In the injection call in the test, your filter must be specified by its name + Filter.
Unit test a controller
Unit test a directive
AngularJS gotchas and traps
Things to do when using html5Mode
Two-way data binding stops working
7 Deadly Sins of AngularJS
Here the include creates a child scope and you can get a name variable, right, but any change to that variable will stay there. You can then access this variable in the include via the 'data' object and see that the two-way binding works perfectly.