Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, March 3, 2017

Angular JS 1 Tutorial

Angular Js 

Controller Responsibilities
--------------------------------
1.Fetching the right data from the server for the current UI
2 Deciding which parts of that data to show to the user
3 Presentation logic, such as how to display elements, which parts of the UI to show, how to style them, etc.
4 User interactions, such as what happens when a user clicks something or how a text input should be validated

Angular Js Life Cycle
-------------------------

1. The HTML is loaded. This triggers requests for all the scripts that are a part of it.
2. After the entire document has been loaded, AngularJS kicks in and looks for the ng-app directive.
3. When it finds the ng-app directive, it looks for and loads the module that is specified and attaches it to the element.
4. AngularJS then traverses the children DOM elements of the root element with the ng-app and starts looking for directives and bind statements.
5. Each time it hits an ng-controller or an ng-repeat directive, it creates what we call a scope in AngularJS. A scope is the context for that element. The scope dictates what each DOM element has access to in terms of functions, variables, and the like.
6. AngularJS then adds watchers and listeners on the variables that the HTML ac‐cesses, and keeps track of the current value of each of them. When that value changes, AngularJS updates the UI immediately.
7. Instead of polling or some other mechanism to check if the data has changed, An‐gularJS optimizes and checks for updates to the UI only on certain events, which can cause a change in the data or the model underneath. Examples of such events include XHR or server calls, page loads, and user interactions like click or type.


a.ng-class:
The ng-class directive is used to selectively apply and remove CSS classes from elements. There are multiple ways of using ng-class, and we will talk about what we feel is the most declarative and cleanest option. The ng-class directive can take strings or objects as values. If it is a string, it simply applies the CSS classes directly.
If it is an object (which we are returning from the function in the controller), An‐gularJS takes a look at each key of the object, and depending on whether the value for that key is true or false, applies or removes the CSS class.

b.ng-show
There are two directives in AngularJS that deal with hiding and showing HTML elements: ng-show and ng-hide. They inspect a variable and, depending on the truthiness of its value, show or hide elements in the UI, respectively. In this case,we say show the assignee span if note.assignee is true. AngularJS treats true,nonempty strings, nonzero numbers, and nonnull JS objects as truthy. So in this case, we get to see the assignee span if the note has an assignee.


Form States:
-----------
a.$invalid :AngularJS sets this state when any of the validations (required, ng-minlength, and others) mark any of the fields within the form as invalid.

b.$valid: The inverse of the previous state, which states that all the validations in the form are currently evaluating to correct.

c.$pristine: All forms in AngularJS start with this state. This allows you to figure out if a user has started typing in and modifying any of the form elements. Possible usage: disabling the reset button if a form is pristine.

d.$dirty :The inverse of $pristine, which states that the user made some changes (he can revert it, but the $dirty bit is set).

e.$error: This field on the form houses all the individual fields and the errors on each form element. We will talk more about this in the following section.

Built-in Angular Js Validators:
-------------------------------
a.required :As previously discussed, this ensures that the field is required, and the field is marked invalid until it is filled out.

b.ng-required: Unlike required, which marks a field as always required, the 

c.ng-required directive allows us to conditionally mark an input field as required based on a Boolean condition in the controller.

d.ng-minlength: We can set the minimum length of the value in the input field with this directive.

e.ng-maxlength: We can set the maximum length of the value in the input field with this directive.

f.ng-pattern: The validity of an input field can be checked against the regular expression pattern specified as part of this directive.
    type="email" :Text input with built-in email validation.
    type="number" :Text input with number validation. Can also have         additional attributes for min and max values of the number itself.
   type="date" :If the browser supports it, shows an HTML datepicker. Otherwise, defaults to a text input. The ngmodel that this binds to will be a date object. This expects the date to be in yyyy-mm-dd format (e.g.,
2009-10-24).
       type="url" :Text input with URL validation.

Common AngularJS Services
---------------------------
1.$window:
The $window service in AngularJS is nothing but a wrapper around the global win‐dow object. The sole reason for its existence is to avoid global state, especially in tests. Instead of directly working with the window object, we can ask for and work with $window. In the unit tests, the $window service can be easily mocked out (avail‐able for free with the AngularJS mocking library).
2.$location:
The $location service in AngularJS allows us to interact with the URL in the
browser bar, and get and manipulate its value. Any changes made to the $location service get reflected in the browser, and any changes in the browser are immediately captured in the $location service. The $location service has the following functions, which allow us to work with the URL:
a.absUrl
A getter that gives us the absolute URL in the browser (called $location.
absUrl()).
b.url
A getter and setter that gets or sets the URL. If we give it an argument, it will set the URL; otherwise, it will return the URL as a string.
c.path
Again, a getter and setter that sets the path of the URL. Automatically adds the forward slash at the beginning. So $location.path() would give us the current path of the application, and $location.path("/new") would set the pathto /new.
d.search
Sets or gets the search or query string of the current URL. Calling $location.search() without any arguments returns the search parameter as an object. Calling $location.search("test") removes the search parameter from the URL, and calling $location.search("test", "abc"); sets the search pa
rameter test to abc.
3.$http

Config function :
------------------
• The config function executes before the AngularJS app executes. So we can be assured that this executes before our controllers, services, and other functions.
• The config function follows the same Dependency Injection pattern, but gets providers injected in. In this case, we ask for the ItemServiceProvider.
• At this point, we can now call functions and set values that the provider exposes.
We are able to the call the disableDefaultItems function that we defined in the
provider.
• The config function could also set up URL endpoints, locale information, routingconfiguration for our application, and so on: things that need to be executed and initialized before our application starts.
• We can try changing the value of shouldHaveDefaults to true (this would come from the server or URL, or some other way usually) to see the effect it has on ourapplication.

Directives :
AngularJS directives are what controls the rendering of the HTML inside an AngularJS application. 

myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */

    directive.template = "My first directive: {{textToInsert}}";

    return directive;
});

$watch()
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
  • A value function
  • A listener function
Here is an example:
$scope.$watch(function() {},
              function() {}
             );


Tuesday, June 28, 2016

Angular Js quetions

1. What are the differences between AngularJS module's Service, Provider and Factory?

Understanding AngularJS Factory, Service and Provider
All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.
From Docs Service/Factory:
  • Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Factory

A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.
app.factory('MyFactory', function() {
    var serviceObj = {};
    //creating an object with methods/functions or variables
    serviceObj.myFunction = function() {
        //TO DO:
    };
    //return that object
    return serviceObj;
});
Usage
It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.

Service

Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties).
app.service('MyService', function() {
    //directly binding events to this context
    this.myServiceFunction = function() {
        //TO DO:
    };
});
Usage
Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.

Provider

A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular.
app.provider('configurableService', function() {
    var name = '';
    //this method can be be available at configuration time inside app.config.
    this.setName = function(newName) {
        name = newName;
    };
    this.$get = function() {
        var getName = function() {
             return name;
        };
        return {
            getName: getName //exposed object to where it gets injected.
        };
    };
});
Usage
When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like devstage or prod
NOTE
Only provider will be available in config phase of angular, while service & factory are not.
Hope this has cleared up your understanding about Factory, Service and Provider.


2.How does data binding work in AngularJS?

By dirty checking the $scope object

Angular maintains a simple array of watchers in the $scope objects. If you inspect any $scope you will find that it contains an array called $$watchers.
Each watcher is an object that contains among other things
  1. An expression which the watcher is monitoring. This might just be an attribute name, or something more complicated.
  2. A last known value of the expression. This can be checked against the current computed value of the expression. If the values differ the watcher will trigger the function and mark the $scope as dirty.
  3. A function which will be executed if the watcher is dirty.

How watchers are defined

There are many different ways of defining a watcher in AngularJS.
  • You can explicitly $watch an attribute on $scope.
    $scope.$watch('person.username', validateUnique);
  • You can place a {{}} interpolation in your template (a watcher will be created for you on the current $scope).
    <p>username: {{person.username}}</p>
  • You can ask a directive such as ng-model to define the watcher for you.
    <input ng-model="person.username />

The $digest cycle checks all watchers against their last value

When we interact with angular through the normal channels (ng-model, ng-repeat, etc) a digest cycle will be triggered by the directive.
A digest cycle is a depth first traversal of $scope and all its children. For each $scope object, we iterate over its $$watchers array and evaluate all the expressions. If the new expression value is different from the last known value, the watcher's function is called. This function might recompile part of the DOM, recompute a value on $scope, trigger an AJAX request, anything you need it to do.
Every scope is traversed and every watch expression evaluated and checked against the last value.

If a watcher is triggered, the $scope is dirty

If a watcher is triggered, the app knows something has changed, and the $scope is marked as dirty.
Watcher functions can change other attributes on $scope or on a parent $scope. If one $watcher function has been triggered, we can't guarantee that our other $scopes are still clean, and so we execute the entire digest cycle again.

If the $digest is dirty, we execute the entire $digest cycle again

We continually loop through the $digest cycle until either the digest cycle comes up clean (all $watch expressions have the same value as they had in the previous cycle), or we reach the digest limit. By default, this limit is set at 10.
If we reach the digest limit Angular will raise an error in the console:
10 $digest() iterations reached. Aborting!

The digest is hard on the machine but easy on the developer

As you can see, every time something changes in an Angular app, Angular will check every single watcher in the $scope hierarchy to see how to respond. For a developer this is a massive productivity boon, as you now need to write almost no wiring code, Angular will just notice if a value has changed.
From the perspective of the machine though this is wildly inefficient and will slow our app down if we create too many watchers. Misko has quoted a figure of about 4000 watchers before your app will feel slow on older browsers.
This limit is easy to reach if you ng-repeat over a large JSON array for example. You can mitigate against this using features like one-time binding to compile a template without creating watchers.