Skip to content

Instantly share code, notes, and snippets.

@muhammadghazali
Last active October 14, 2022 06:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save muhammadghazali/8613512 to your computer and use it in GitHub Desktop.
Save muhammadghazali/8613512 to your computer and use it in GitHub Desktop.
Notes on AngularJS

What is AngularJS

  • AngularJS is not a library, it's a framework that embraces extending HTML into a more expressive and readable format
  • AngularJS is a structural framework for dynamic web apps
  • A framework that lets you use HTML as your template language and extend HTML's syntax to express your application's components clearly and succinctly
  • Angular is an opinionated framework on how a CRUD application should be built

Use AngularJS to build CRUD application

  • Angular was built for the CRUD application in mind. Games and GUI editors are examples of applications with intensive and tricky DOM manipulation. These kinds of apps are different from CRUD apps, and as a result are probably not a good fit for Angular

http://docs.angularjs.org/guide/overview

Introduction to AngularjS

  • Angular is pure client-side technology, written entirely in JavaScript.
  • Angular is designed primarily for developing single-page apps.

Things I Wish I Were Told About Angular.js

  • Angular.js does not force you to use its module system
  • Understand how Angular modules works before you start
  • You need to understand how $scope works
  • When You Manipulate DOM in Controller, Write Directives
  • And the best part is, your controller does not need to know the existence of directives: communications are achieved through scope sharing and $scope events.
  • put control logic in directive controller, and DOM logic in link function; scope sharing is the glue.
  • The only unit test that requires some DOM manipulation is directive.

About MVC in AngularJS

  • Along with services and dependency injection, MVC makes angular applications better structured, easier to maintain and more testable.

Understanding the Model Component

  • Depending on the context of the discussion in the Angular documentation, the term model can refer to either a single object representing one entity (for example, a model called "phones" with its value being an array of phones) or the entire data model for the application (all entities).

Undestanding the Controllers Component

Understanding Controllers

  • In Angular, a Controller is a JavaScript constructor function

Use Controllers to:

  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Scope Inheritance

  • If the child controller are having the same properties with the parent controller, then it will override the parent properties.
  • Controller is the business logic behind views
  • The purpose of controllers is to expose variables and functionality to expressions and directives.
  • The primary responsibility of a controller is to initialize scope objects.
  • In practice, the initialization logic consists of the following responsibilities: providing initial values and augmenting $scope with UI-specific behavior (functions).
  • Controllers in AngularJS are regular JavaScript functions.
  • Directive extend HTML with custom attributes and elements. We use Directive to apply special behaviour to attributes or elements in the HTML.

Notes on creating directives

  • Use the module.directive API to register a directive
  • The factory function should return an object
  • The factory function is invoked only once when the $compiler matches the directive for the first time.
  • Perform any initialization work on factory function
  • Prefer using the definition object over returning a function
  • Prefix your own directives with 2 or 3 words, and avoid prefix your own directives with ng- or they might conflict with directives included in a future version of Angular.
  • Use the templateUrl option if the size of the template relatively big.

Notes on directive restrict option

  • When you create a directive, it is restricted to attribute only by default.
  • Use an element restrict option (E) when you are creating a component that is in control of the template. The common case for this is when you are creating a Domain-Specific Language for parts of your template.
  • Use an attribute restrict option (A) when you are decorating an existing element with new functionality.
  • Notes on directive scope option

Notes on directive scope option

  • Use the scope option to create isolate scopes when making components that you want to reuse throughout your app

Notes on manupulating the DOM

  • Directives that want to modify the DOM typically use the link option.
  • When a DOM node that has been compiled with AngularJS's compiler is destroyed, it emits a $destroy event.

Notes on creating directives that communicate

  • use controller option when you want to expose an API to other directives. Otherwise use link.
  • When other directives try to communicate wit other directives via exposed API, they will received controller as their fourth argument link function. For example function (scope, element, attrs, myTabsCtrl) { ... }

Notes on rendering model values

  • Use ngBind directive to hide expressions before AngularJS has a chance of processing them on he initial page load. This prevents UI flickering and provides better user experience.

Notes on conditional display

Showing and hiding parts of the DOM based on some conditions is a common requirement. AngularJS comes equipped with four different sets of directives for this occasion:

  • ng-show/ng-hide
  • ng-switch-*
  • ng-if
  • ng-include

Notes on Including blocks of content conditionally

  • The ng-include directive is creating a new scope for each partial it includes.
  • The ng-include directive accepts an experession as its argument, so you need to pass a quoted string if you plan to use a fixed value pointing to a partial, for example: <div ng-include="'header.tpl.html'"></div>.

ngRepeat directive

Rendering collections with ngRepeat

  • It will iterate over a collection of items stamping out a new DOM element for each entry in a collection.
  • It will constantly monitor the source of data to re-render a template in response to changes.
  • The ng-repeat directive behaves more like an observer of a data that tries to map entries in a collection to DOM nodes. The process of data-observing is continuous.
  • The ng-repeat directive creates a new scope for each element of a collection it iterates over.

Special variables in ngRepeat

Use special variables to determine a position of each element within a collection:

  • $index: It will be set to a number indicating inhdex of an element in a collection (indexes start at 0)
  • $first, $middle, $last: These variables will get a Boolean value according to element's position

Demo of special variables

Iterating over an object's properties

We can use ngRepeat to iterate over properties of an object. The syntax is:

  <li ng-repeat="(name, value) in user">
    Property {{$index}} with {{name}} has value {{value}}
  </li>

Demo of iterating over an object's properties

The ng-repeat directive will, before outputting results, sort property names alphabetically. This behavior can't be changed so there is no way of controlling the iteration order while using ng-repeat with objects.

ngClassEven and ngClassOdd

Use ng-class-even and ng-class-odd to create a zebra-striping in a list to improve readability.

<tr ng-repeat="menu in menus" ng-class-even="'even'" ng-class-odd="'odd'">
  . . .
</tr>

DOM event handlers

AngularJS has the built-in supports for the different events with the following directives:

Filter

A filter is nothing more than a global, named function that is invoked in view using the pipe | symbol with parameters separated by the colon : character.

Advantages of filters are two-fold:

  • they don't require registration of functions on a scope (so are readily available for each and every template)
  • usually offer more convenient syntax as compared to regular function calls

We can devide built-in filters into two groups: formatting filters and array-transforming filters.

The formatting filters:

  • currency: It formats numbers with two decimal places and a currency symbol.
  • date: It formats date according to a specified data format.
  • number: It will format input with a number of decimal places specified as an argument to the filter.
  • lowercase and uppercase: Those filters can be used to format strings into their lowercase or uppercase form.
  • json: This filter is mostly useful for debugging purposes as it can assure pretty-print for JavaScript objects.

The array-transforming filters:

  • limitTo: It returns an array shrunk to the specified size.
  • filter: A general purpose filtering utility.
  • orderBy: Ordering filter can be used to sort individual elements in an array based on the provided criteria.

The array-transforming filters work on arrays only except limitTo can cope with strings as well.

  • Model is the data that i

Module

  • A module acts as container for other AngularJS managed objects (controllers, services and son on).
  • To define new module provide it's name as the very first argument to the module function call. The second argument makes it possible to express a dependency on other modules.
  • A call to the angular.module function returns an instance of newly created module.
  • Globally-defined controller's constructor functions are only good for quick-code examples and fast prototpying. Never user globally-defined controller functions in larger, real-life applications.

Dependency Injection

AngularJS has the dependency injection (DI) engine built-in. To perform the following activities:

  • Understand a need for a collaborator expressed by objects.
  • Find a needed collaborator.
  • Wire up objects together into a fully-functional application

Modules Lifecycle

AngularJS splits module's lifecycle into two phases, which are as follows:

  • The configuration phase
  • The run phase

The configuration phase

  • It is the phase where all the recipes are collected and configured.
  • The configuration phase allows us to do the last moment tweaks to the object's creation formula
  • AngularJS can have multiple configure blocks

The run phase

  • Allows us to register any work that should be executed upon the application's bootstrap.
  • AngularJS can have multiple run blocks

AngularJS modules and files

There are basically three approaches we could take to relate individual files and AngularJS modules:

  • Allow multiple AngularJS modules in one JavaScript file
  • Have AngularJS modules spanning multiple JavaScript files
  • Define exactly one AngularJS module per JavaScript file
  • Scope is context where the model is stored so that controllers, directives, and expressions can access it. The values that are stored in variables on the scope are referred to as the model.
  • AngularJS will create a new instance of the Scope class whenever it encounters a scope-creating directive in the DOM tree. The ng-controller directive is an example of scope-creating directive.
  • Each $scope is an instance of the Scope class.
  • The scope class has methods that control the scope's lifecycle, provide event-propagation facility, and support the template rendering process.
  • A new $scope was created by the ng-controller directive using the Scope.$new() method call.
  • $rootScope instance gets created when a new application
  • When Angular starts your application, it parses and processes this new markup from the template using the so called compiler. The loaded, transformed, and rendered DOM is then called the view. So, the view and template are really a different things. The template is HTML with additional markup, and the view is the output of compile process.
  • AngularJS framework rely on the HTML for its template syntax.
  • It depends on the browser to parse the template's text.
  • After browser is done transforming the markup's text to the DOM tree, AngularJS kicks in and traverses the parsed DOM structure.
  • We should ensure that the markup written on the template represents valid HTML.
  • AngularJS promotes a declarative approach to UI construction.
  • Templates are focused on describing a desired effect
  • AngularJS heavily promotes declarative style of programming for templates and impervative one for the JavaScript code (controllers and business logic)
  • Directives in AngularJS templates declaratively express the desired effect, so we freed from providing step-by-step instructions on how to change individual properties of DOM elements (as is often the case in applications based on jQuery).
  • As a rule of thumb, one should never manipulate the DOM elements in AngularJS controllers. Getting a reference to a DOM element in a controller and manipulating element's properties indicate imperative approach to UI - something that goes againts AngularJS way of building UIs.
  • Expressions access the variables and functions from the scope. An expression in a template is a JavaScript-like code snippet that allows to read and write variables that live in a scope.
  • AngularJS is well equipped to communicate with various back-ends using XMLHttpRequest (XHR) and JSONP requests.
  • Use $http service for issuing XHR and JSONP calls or specialized $resource service to easily target RESTful endpoints.

A generic way to issuing XHR request

To issuing XHR request in generic way, we can use the $http(configObject) function with the config object can have the following properties:

  • method: HTTP method to be issued
  • url: URL to be targeted with a request
  • params: parameters to be added to the URL query string
  • headers: additional headers to be added to a request
  • timeout: timeout (in ms) after which a XHR request will be dropped
  • cache: enables XHR GET request caching
  • transformRequest, transformResponse: transformation functions that allows us to pre-process and post-process data exchanged with a back-end.

Dedicated shortcut methods to issue XHR request

  • GET: $http.get(url, config)
  • POST: $http.post(url, data, config)
  • PUT: $http.put(url, data, config)
  • DELETE: $http.delete(url, config)
  • HEAD: $http.head

Use those shortcut methods since it's more concise and easier way to read code, and use this form over the generic one whenever possible.

Promise API

  • To handle multiple asynchronous events use Promise API.
  • The main idea behind the Promise API is to bring to the asynchronous world the same ease functions calls chaining and error handling as we can enjoy in the synchronous programming world.
  • AngularJS comes with the $q service a very lightweight Promise API implementation.

$q service basics

$q.defer() method returns a deferred object to represents a task that will be completed or fail in the future. The deferred object has two roles:

  • It holds a promise object (in the promise property). Promises are placeholders for the future results (success or failure) of a deferred task.
  • It exposes methods to trigger future task completion (resolve) or failure (reject).
  • There are always two players in the Promise API: one that controls future task execution (can invoke methods on the deferred object) and another one that depends on the results of the future task execution (holds onto promised results).
  • To register a callback the then(successCallback, errorCallback) method is used. If the error callback is omitted and a future task fails, this failure will be silently ignored.

Promises are first-class JavaScript objects

Promises are first-class JavaScript objects, we can pass them around as arguments and return them from function calls. This allows us to easily encapsulate asynchronous operations as service.

  • Use ngModel to specify the bindings on inputs, so changes to the value of the input are reflected back in the model
  • Use [ngRequired](http://docs.angularjs.org/api/ng/directive/input) attribute to set the input as required input.

Handling form submission events

  • When tyring to submitting forms directly to the server you should include an action attribute on a form
  • When trying to handle the submission on the client side by calling a function on the scope, then remove the action attribute on a form. Trigger the client-side function by using ngClick directive on a button or the ngSubmit directive on the form.
  • Warning: Don't use both the ngSubmit and ngClick directives on the same form because the browser will trigger both directives and you will get double submission.
  • Use ngSubmit only on a form that has only one input and not more than one button, such as our search form.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment