Skip to content

Instantly share code, notes, and snippets.

@ethanjiezhou
Created May 12, 2016 17:14
Show Gist options
  • Save ethanjiezhou/43fae61df6f9076399a1860bf0de3e4e to your computer and use it in GitHub Desktop.
Save ethanjiezhou/43fae61df6f9076399a1860bf0de3e4e to your computer and use it in GitHub Desktop.
Q&A GUIDE - AngularJS
  1. What is “promise” and "call back function"? - https://blog.jcoglan.com/2013/04/01/callbacks-promises-and-simplicity/ - http://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript

  2. Difference between $http and $ajax? - http://stackoverflow.com/questions/20860207/angularjs-http-vs-jquery-ajax - http://stackoverflow.com/questions/12131659/from-jquery-ajax-to-angular-http

  3. Relation between $http and "promises"? - http://stackoverflow.com/questions/16855836/angularjs-http-get-then-and-binding-to-a-list - http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html

  4. Difference between “service”, “factory”, and “provider”? - http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/ - http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory

  5. What are the benefits of using a JS framework? - http://jster.net/blog/why-should-you-use-client-side-mvc-framework#.VDoRvPldX-s - https://www.planbox.com/blog/development/coding/the-benefits-of-javascript-mvc.html

  6. Everything you need to know about “promises API”, end to end testing, unit testing - http://www.pluralsight.com/courses/testing-angularjs-from-scratch - http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html - http://quickleft.com/blog/angularjs-unit-testing-for-real-though - https://docs.angularjs.org/api/ng/service/$q - http://www.html5rocks.com/en/tutorials/es6/promises/ - http://andyshora.com/promises-angularjs-explained-as-cartoon.html - http://angular.github.io/protractor/#/ - http://lostechies.com/gabrielschenker/2014/04/18/angular-jspart-14-end-to-end-tests/ - http://www.sitepoint.com/unit-and-e2e-testing-in-angularjs/ - http://www.ng-newsletter.com/posts/practical-protractor.html - http://www.thoughtworks.com/insights/blog/testing-angularjs-apps-protractor - http://www.smashingmagazine.com/2014/10/07/introduction-to-unit-testing-in-angularjs/ - http://jasmine.github.io/2.0/ajax.html

  7. Differences between using scope.$watch and scope.$apply? - http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply - http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/ - http://www.bennadel.com/blog/2658-using-scope-watch-to-watch-functions-in-angularjs.htm - http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

  8. Performance tuning for AngularJS application? - http://tech.small-improvements.com/2013/09/10/angularjs-performance-with-large-lists/ - http://stackoverflow.com/questions/15643467/how-to-speed-up-an-angularjs-application - http://www.binpress.com/tutorial/speeding-up-angular-js-with-simple-optimizations/135

  9. Everything about custom directives - http://thecodebarbarian.wordpress.com/2013/09/23/the-8020-guide-to-writing-angularjs-directives/ - http://blog.brunoscopelliti.com/use-cases-of-angularjs-directives - http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/ - http://blog.brunoscopelliti.com/angularjs-directive-to-check-that-passwords-match - http://blog.brunoscopelliti.com/form-validation-the-angularjs-way - http://blog.brunoscopelliti.com/a-directive-to-manage-file-upload-in-an-angularjs-application

  10. Submitting form in AngularJS way - http://scotch.io/tutorials/javascript/submitting-ajax-forms-the-angularjs-way

  11. Why is this project called "AngularJS"? Why is the namespace called "ng"? - Because HTML has Angular brackets and "ng" sounds like "Angular"

  12. Is AngularJS a library, framework, plugin or a browser extension? - AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library. AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension

  13. Why to choose AngularJS Javascript Framework for front-end web development? - http://theprofessionalspoint.blogspot.in/2014/02/why-to-choose-angular-js-javascript.html

  14. What are the key features of AngularJS? ######Scope The job of the Scope is to detect changes to model objects and create an execution context for expressions. There is one root scope for the application (ng-app) with hierarchical children scopes. It marshals the model to the view and forwards events to the controller ######Controller The Controller is responsible for construction of the model and connects it to the view (HTML). The scope sits between the controller and the view. Controllers should be straightforward and simply contain the business logic needed for a view. Generally you want thin controllers and rich services. Controllers can be nested and handle inheritance. The big difference in AngularJS from the other JavaScript frameworks is there is no DOM manipulation in controllers. It is something to unlearn when developing in AngularJS ######Model In AngularJS, a Model is simply a JavaScript object. No need to extend anything or create any structure. This allows for nested models - something that Backbone doesn’t do out-of-the-box ######View The View is based on DOM objects, not on strings. The view is the HTML. HTML is declarative – well suited for UI design. The View should not contain any functional behavior. The flexibility here is to allow for multiple views per Controller ######Services The Services in AngularJS are singletons that perform common tasks for web applications. If you need to share common functionality between Controllers, then use Services. Built-in AngularJS, Services start with a $. There are several ways to build a service: Service API, Factory API, or the $provide API ######Data Binding Data Binding in AngularJS is a two-way binding between the View and the Model. Automatic synchronizing between views and data models makes this really easy (and straightforward) to use. Updating the model is reflected in View without any explicit JavaScript code to bind them together, or to add event listeners to reflect data changes ######Directives Now this is cool. AngularJS allows you to use Directives to transform the DOM or to create new behavior. A directive allows you to extend the HTML vocabulary in a declarative fashion. The ‘ng’ prefix stands for built-in AngularJS directives. The App (ng-app), Model (ng-model), the Controller (ng-controller), etc. are built into the framework. AngularJS allows for building your own directives. Building directives is not extremely difficult, but not easy either. There are different things that can be done with them. Please check out AngularJS’s documentation on directives ######Filters The Filters in AngularJS perform data transformation. They can be used to do formatting (like I did in my Directives example with padding zeros), or they can be used to do filter results ######Validation AngularJS has some built-in validation around HTML5 input variables (text, number, URL, email, radio, checkbox) and some directives (required, pattern, minlength, maxlength, min, max). If you want to create your own validation, it is just as simple as creating a directive to perform your validation ######Testable Testing is a big concern for enterprise applications. There are several different ways to write and run tests against JavaScript code, thus against AngularJS. The developers at AngularJS advocate using Jasmine tests ran using Testacular. I have found this method of testing very straightforward and, while writing tests may not be the most enjoyable, it is just as importable as any other piece of developing an application

  15. What is $scope in AngularJS? - $scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events

  16. Can you explain the concept of scope hierarchy? How many scopes can an application have? - Each Angular application has exactly one root scope, but may have several child scopes. The application can have multiple scopes, because child controllers and some directives create new child scopes. When new scopes are created, they are added as children of their parent scope. This creates a hierarchical structure similar to the DOM where they're attached.

- When Angular evaluates a bound variable like say {{firstName}}, it first looks at the scope associated with the given       element for the firstName property. If no such property is found, it searches the parent scope and so on until the root       scope is reached. In JavaScript this behavior is known as prototypical inheritance, and child scopes prototypically           inherit from their parents. The reverse is not true. i.e. the parent can't see it's children's bound properties
  1. Is AngularJS a templating system? - At the highest level, Angular does look like a just another templating system. But there is one important reason why the Angular templating system is different, that makes it very good fit for application development: bidirectional data binding. The template is compiled in the browser and the compilation step produces a live view. This means you, the developers, don't need to write code to constantly sync the view with the model and the model with the view as in other templating systems

  2. Do I need to worry about security holes in AngularJS? - Like any other technology, AngularJS is not impervious to attack. Angular does, however, provide built-in protection from basic security holes including cross-site scripting and HTML injection attacks. AngularJS does round-trip escaping on all strings for you and even offers XSRF protection for server-side communication - AngularJS was designed to be compatible with other security measures like Content Security Policy (CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the possible attack vectors and we highly recommended their use

  3. What's Angular's performance like? - The startup time heavily depends on your network connection, state of the cache, browser used and available hardware, but typically we measure bootstrap time in tens or hundreds of milliseconds - The runtime performance will vary depending on the number and complexity of bindings on the page as well as the speed of your backend (for apps that fetch data from the backend). Just for an illustration we typically build snappy apps with hundreds or thousands of active bindings

  4. Does Angular use the jQuery library? - Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite - Due to a change to use on()/off() rather than bind()/unbind(), Angular 1.2 only operates with jQuery 1.7.1 or above

  5. What are the key differences between AngularJS and jQuery? - http://theprofessionalspoint.blogspot.in/2014/02/angularjs-vs-jquery-difference-between.html

  6. How will you compare AngularJS with other Javascript frameworks like Ember and Backbone? - http://theprofessionalspoint.blogspot.in/2014/02/angularjs-vs-ember-vs-backbone-which.html

  7. What is MVC? What do Model and View stand for? - Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces - A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified - A view requests information from the model that it uses to generate an output representation to the user - A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document)

  8. What’s Two-way Data Binding in AngularJS? - Automatic synchronization of data between the model and view components. The typical example is, ```html

    Hello, {{ yourName }}!

</div>    
```
- Change content of `<input>` automatically update model, change model automatically update content of view `<h1>`
  1. What is the difference between compile and link?

  2. What is injector in angular?

  3. What is the difference between factory, service and provider in angularjs?

  4. What is a directive and why it is used?

  5. What is $apply and $digest? How they are used in angular?

  6. What are modules in AngularJS?

  7. How data binding works in Angular and what is "scope"?

  8. How to approach unit testing for AngularJS components?

  9. What is AngularJS?

    • AngularJS is an open-source JavaScript framework developed by Google. It helps you to create single-page applications or one-page web applications that only require HTML, CSS, and JavaScript on the client side. It is based on MV-* pattern and allow you to build well structured, easily testable, and maintainable front-end applications.
    • AngularJS has changed the way to web development. It is not based on jQuery to perform its operations. In spite of using ASP.NET Web form, ASP.NET MVC, PHP, JSP, Ruby on Rails for web development, you can do your complete web development by using most powerful and adaptive JavaScript Framework AngularJS. There is no doubt, JavaScript frameworks like AngularJS, Ember etc. are the future of web development
  10. Why to use AngularJS?

    • There are following reasons to choose AngularJS as a web development framework:
      • It is based on MVC pattern which helps you to organize your web apps or web application properly
      • It extends HTML by attaching directives to your HTML markup with new attributes or tags and expressions in order to define very powerful templates
      • It also allows you to create your own directives, making reusable components that fill your needs and abstract your DOM manipulation logic
      • It supports two-way data binding i.e. connects your HTML (views) to your JavaScript objects (models) seamlessly. In this way any change in model will update the view and vice versa without any DOM manipulation or event handling
      • It encapsulates the behaviour of your application in controllers which are instantiated with the help of dependency injection
      • It supports services that can be injected into your controllers to use some utility code to fulfil your need. For example, it provides $http service to communicate with REST service
      • It supports dependency injection which helps you to test your angular app code very easily
      • Also, AngularJS is mature community to help you. It has widely support over the internet
  11. Why this project is called "AngularJS"?

    • Html has angle brackets i.e. <,> and ng sound like Angular. That’s why it is called AngularJS
  12. What are the advantages of AngularJS?

    • There are following advantages of AngularJS:
      • Data Binding - AngularJS provides a powerful data binding mechanism to bind data to HTML elements by using scope
      • Customize & Extensible - AngularJS is customized and extensible as per you requirement. You can create your own custom components like directives, services etc.
      • Code Reusability - AngularJS allows you to write code which can be reused. For example custom directive which you can reuse
      • Support – AngularJS is mature community to help you. It has widely support over the internet. Also, AngularJS is supported by Google which gives it an advantage
      • Compatibility - AngularJS is based on JavaScript which makes it easier to integrate with any other JavaScript library and runnable on browsers like IE, Opera, FF, Safari, Chrome etc.
      • Testing - AngularJS is designed to be testable so that you can test your AngularJS app components as easy as possible. It has dependency injection at its core, which makes it easy to test
  13. How AngularJS is different from other JavaScript Framework?

    • Today, AngularJS is the most popular and dominant JavaScript framework for professional web development. It is well suited for small, large and any sized web app and web application
    • AngularJS is different from other JavaScript framework in following ways:
      • AngularJS mark-up lives in the DOM
      • AngularJS uses plain old JavaScript objects (POJO)
      • AngularJS is leverages with Dependency Injection
  14. What IDEs you can use for AngularJS development?

    • AngularJS development can be done with the help of following IDEs:
      • Visual Studio 2012, 2013, 2015 or higher
      • Eclipse
      • WebStorm
      • Sublime Text
      • TextMate
  15. Does AngularJS has dependency on jQuery?

    • AngularJS has no dependency on jQuery library. But it can be used with jQuery library
  16. How to use jQuery with AngularJS?

    • By default AngularJS use jQLite which is the subset of jQuery. If you want to use jQuery then simply load the jQuery library before loading the AngularJS. By doing so, Angular will skip jQLite and will started to use jQuery library
  17. Compare the features of AngularJS and jQuery?

    • The comparison of AngularJS and jQuery features are given below:
    Features jQuery AngularJS
    Abstract The DOM Y Y
    Animation Support Y Y
    AJAX/JSONP Y Y
    Cross Module Communication Y Y
    Deferred Promises Y Y
    Form Validation N Y
    Integration Test Runner N Y
    Unit Test Runner Y Y
    Localization N Y
    MVC Pattern N Y
    Template N Y
    Two-way Binding N Y
    One-way Binding N Y
    Dependency Injection N Y
    Routing N Y
    Restful API N Y
  18. What is jQLite or jQuery lite?

    • jQLite is a subset of jQuery that is built directly into AngularJS. jQLite provides you all the useful features of jQuery. In fact it provides you limited features or functions of jQuery
    • Here is a table of supported jQuery methods by jQLite:
    jQuery Method Limitation, if any
    addClass()
    after()
    append()
    attr()
    bind() Does not support namespace, selectors and eventData
    children Does not support selectors
    clone()
    contents()
    css()
    data()
    detach()
    empty()
    eq()
    find() Limited to lookups by tag name
    hasClass()
    html()
    text() Does not support selectors
    on() Does not support namespace, selectors and eventData
    off() Does not support namespace, selectors
    one() Does not support namespace, selectors
    parent() Does not support selectors
    prepend()
    prop
    ready()
    remove
    removeAttr()
    removeClass()
    removeData()
    replaceWith()
    toggleClass()
    triggerHandler() Passes a dummy event object to handlers
    unbind() Does not support names
    val()
    wrap()
  19. How to access jQLite or jQuery with AngularJS? OR What is angular.element() in AngularJS?

    • jQuery lite or the full jQuery library if available, can be accessed via the AngularJS code by using the element() function in AngularJS. Basically, angular.element() is an alias for the jQuery function
    angular.element() === jQuery() === $()

    For example:

    <html>
    
    <head>
        <script src="lib/angular.js"></script>
        <script type="text/javascript">
        var app = angular.module('app', []);
        app.controller("mainCtrl", function($scope, $element) {
            $scope.clickme = function() {
                var elem = angular.element(document.querySelector('#txtName'));
                console.log(elem.val()) // console the value of textbox
            };
        });
        </script>
    </head>
    
    <body ng-app="app">
        <div ng-controller="mainCtrl">
            <input type="text" id="txtName" value="Shailendra Chauhan" />
            <button type="button" ng-click="clickme()">Click me</button>
        </div>
    </body>
    
    </html>
    • When you will click on the "Click me" button, the value of textbox will be logged on console
  20. Is AngularJS a library, framework, plugin or a browser extension?

    • AngularJS is a first class JavaScript framework which allows you to build well structured, easily testable, and maintainable front-end applications. It is not a library since library provides you limited functionality or has dependencies to other libraries
    • It is not a plugin or browser extension since it is based on JavaScript and compatible with both desktop and mobile browsers
  21. What browsers AngularJS support?

    • The latest version of AngularJS 1.3 support Safari, Chrome, Firefox, Opera 15+, IE9+ and mobile browsers (Android, Chrome Mobile, iOS Safari, Opera Mobile)
    • AngularJS 1.3 has dropped support for IE8 but AngularJS 1.2 will continue to support IE8
  22. What is the size of angular.js file?

    • The size of the compressed and minified file is < 36KB
  23. What are AngularJS features?

    • The features of AngularJS are listed below:
      • Modules
      • Directives
      • Templates
      • Scope
      • Expressions
      • Data Binding
      • MVC (Model, View & Controller)
      • Validations
      • Filters
      • Services
      • Routing
      • Dependency Injection
      • Testing
  24. How AngularJS handle the security?

    • AngularJS provide following built-in protection from basic security holes:
      • Prevent HTML injection attacks
      • Prevent Cross-Site-Scripting (CSS) attacks
      • Prevent XSRF protection for server side communication
    • Also, AngularJS is designed to be compatible with other security measures like Content Security Policy (CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the possible attacks
  25. What are Modules in AngularJS?

    • AngularJS modules are containers just like namespace in C#. They divide an angular app into small, reusable and functional components which can be integrated with other angular app. Each module is identified by a unique name and can be dependent on other modules. In AngularJS, every web page (view) can have a single module assigned to it via ng-app directive
    • Creating an AngularJS module
    <script type="text/javascript">
    	// defining module angular.module('myApp', []);
    	// OR defining module which has dependency on other modules
    	angular.module('myApp', ['dependentModule1', 'dependentModule2']);
    </script>
    • Using an AngularJS module into your app
    <html ng-app="myApp">
    
    <head></head>
    
    <body></body>
    
    </html>
  26. What components can be defined within AngularJS modules?

    • You can define following components with in your angular module:

    - Directive
    - Filter
    - Controller
    - Factory
    - Service
    - Provider
    - Value
    - Config settings and Routes
    
  27. What is core module in AngularJS?

    • ng is the core module in angular. This module is loaded by default when an angular app is started. This module provides the essential components for your angular app like directives, services/factories, filters, global APIs and testing components
  28. How angular modules load the dependencies?

    • An angular module use configuration and run blocks to inject dependencies (like providers, services and constants) which get applied to the angular app during the bootstrap process
  29. What is difference between config() and run() method in AngularJS?

    • Configuration block: This block is executed during the provider registration and configuration phase. Only providers and constants can be injected into configuration blocks. This block is used to inject module wise configuration settings to prevent accidental instantiation of services before they have been fully configured. This block is created using config() method
    angular.module('myModule', [])
    	.config(function(injectables) { // provider-injector
        // This is an example of config block.
        // You can have as many of these as you want.
        // You can only inject Providers (not instances) // into config blocks.
    })
    	.run(function(injectables) { // instance-injector // This is an example of a run block.
        // You can have as many of these as you want.
        // You can only inject instances (not Providers) // into run blocks
    });
    • Run block: This block is executed after the configuration block. It is used to inject instances and constants. This block is created using run() method. This method is like as main method in C or C++. The run block is a great place to put event handlers that need to be executed at the root level for the application. For example, authentication handlers
  30. When dependent modules of a module are loaded?

    • A module might have dependencies on other modules. The dependent modules are loaded by angular before the requiring module is loaded
    • In other words the configuration blocks of the dependent modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it
  31. What is Global API?

    • Global API provides you global functions to perform common JavaScript tasks such as comparing objects, deep copying, iterating through objects, and converting JSON data etc. All global functions can be accessed by using the angular object. The list of global functions is given below:
    Name Description
    angular.lowercase Converts the specified string to lowercase
    angular.uppercase Converts the specified string to uppercase
    angular.forEach Invokes the iterator function once for each item in obj collection, which can be either an object or an array
    angular.isUndefined Determines if a reference is undefined
    angular.isDefined Determines if a reference is defined
    angular.isObject Determines if a reference is an Object
    angular.isString Determines if a reference is a String
    angular.isNumber Determines if a reference is a Number
    angular.isDate Determines if a value is a date
    angular.isArray Determines if a reference is an Array
    angular.isFunction Determines if a reference is a Function
    angular.isElement Determines if a reference is a DOM element (or wrapped jQuery element)
    angular.copy Creates a deep copy of source, which should be an object or an array
    angular.equals Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects
    angular.bind Returns a function which calls function fn bound to self
    angular.toJson Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since angular uses this notation internally
    angular.fromJson Deserializes a JSON string
    angular.bootstrap Use this function to manually start up angular application
    angular.reloadWithDebugInfoUs Use this function to reload the current application with debug information turned on
    angular.injector Creates an injector object that can be used for retrieving services as well as for dependency injection
    angular.element Wraps a raw DOM element or HTML string as a jQuery element
    angular.module Used for creating, registering and retrieving Angular modules
  32. What is Angular Prefixes $ and $$?

    • To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. So, do not use the $ or $$ prefix in your code
  33. What are Filters in AngularJS?

    • Filters are used to format data before displaying it to the user. They can be used in view templates, controllers, services and directives. There are some built-in filters provided by AngularJS like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters
    • Filter Syntax:
    {{ expression | filter}}
    • Filter Example:
    <script type="text/javascript">
    	{{ 14 | currency }} // returns $14.00
    </script>
  34. What are Expressions in AngularJS?

    • AngularJS expressions are much like JavaScript expressions, placed inside HTML templates by using double braces such as: {{expression}}. AngularJS evaluates expressions and then dynamically adds the result to a web page. Like JavaScript expressions, they can contain literals, operators, and variables
    • These are some valid AngularJS expressions:
      • {{ 1 + 2 }}
      • {{ x + y }}
      • {{ x == y }}
      • {{ x = 2 }}
      • {{ user.Id }}
  35. How AngularJS expressions are different from the JavaScript expressions?

    • AngularJS expressions are much like JavaScript expressions but they are different from JavaScript expressions in the following ways:
      1. Angular expressions can be added inside the HTML templates
      2. Angular expressions doesn't support control flow statements (conditionals, loops, or exceptions)
      3. Angular expressions support filters to format data before displaying it
  36. What are Directives in AngularJS?

    • AngularJS directives are a combination of AngularJS template markups (HTML attributes or elements, or CSS classes) and supporting JavaScript code. The JavaScript directive code defines the template data and behaviors of the HTML elements
    • AngularJS directives are used to extend the HTML vocabulary i.e. they decorate html elements with new behaviors and help to manipulate html elements attributes in interesting way
    • There are some built-in directives provided by AngularJS like as ng-app, ng-controller, ng-repeat, ng-model etc.
  37. What is the role of ng-app, ng-init and ng-model directives?

    • The main role of these directives is explained as:
      • ng-app: Initialize the angular app
      • ng-init: Initialize the angular app data
      • ng-model: Bind the html elements like input, select, text area to angular app model
  38. How to create custom directives in AngularJS?

    • You can create your own custom directive by using following syntax:
    var app = angular.module('app', []);
    // creating custom directive syntax
    app.directive("myDir", function() {
        return {
            restrict: "E", // define directive type like E = element, A = attribute, C = class, M = comment
            scope: { // create a new child scope or an isolate scope
                title: '@' // @ reads the attribute value, // = provides two-way binding, // & works with functions
            },
            template: "<div>{{ myName }}</div>", // define HTML markup
            templateUrl: 'mytemplate.html', // path to the template, used by the directive replace: true | false, // replace original markup with template yes/no transclude: true | false, // copy original HTML content yes/no
            controller: function(scope) { // define controller, associated with the directive template
                // TODO:
            },
            link: function(scope, element, attrs, controller) { // define function, used for DOM manipulation
                // TODO:
            }
        }
    });
  39. What are different ways to invoke a directive?

    • There are four methods to invoke a directive in your angular app which are equivalent
    Method Syntax
    As an attribute <span my-directive></span>
    As a class <span class="my-directive: expression;"></span>
    As an element <my-directive></my-directive>
    As a comment <!-- directive: my-directive expression -->
  40. What is restrict option in directive?

    • The restrict option in angular directive, is used to specify how a directive will be invoked in your angular app i.e. as an attribute, class, element or comment
    • There are four valid options for restrict:
    'A' (Attribute) - <span my-directive></span>
    'C' (Class) - <span class="my-directive:expression;"></span> 
    'E' (Element) - <my-directive></my-directive>
    'M' (Comment) - <!-- directive: my-directive expression -->
  41. Can you define multiple restrict options on a directive?

    • You can also specify multiple restrict options to support more than one methods of directive invocation as an element or an attribute. Make sure all are specified in the restrict keyword as: restrict: 'EA'
  42. What is auto bootstrap process in AngularJS? / How AngularJS is initialized automatically?

    • Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is downloaded to the browser and the document.readyState is set to complete. At this point AngularJS looks for the ng-app directive which is the root of angular app compilation and tells about AngularJS part within DOM. When the ng-app directive is found then Angular will:
      • Load the module associated with the directive
      • Create the application injector
      • Compile the DOM starting from the ng-app root element
    • This process is called auto-bootstrapping
    • Example:
    <html>
    
    <body ng-app="myApp">
        <div ng-controller="Ctrl">Hello {{msg}}!</div>
        <script src="lib/angular.js"></script>
        <script>
    	    var app = angular.module('myApp', []);
    	    app.controller('Ctrl', function($scope) {
    	        $scope.msg = 'World';
    	    });
        </script>
    </body>
    
    </html>
  43. What is manual bootstrap process in AngularJS? / How AngularJS is initialized manually?

    • You can manually initialized your angular app by using angular.bootstrap() function. This function takes the modules as parameters and should be called within angular.element(document).ready() function. The angular.element(document).ready() function is fired when the DOM is ready for manipulation
    • Example:
    <html>
    
    <body>
        <div ng-controller="Ctrl">Hello {{msg}}!</div>
        <script src="lib/angular.js"></script>
        <script>
    	    var app = angular.module('myApp', []);
    	    app.controller('Ctrl', function($scope) {
    	        $scope.msg = 'World';
    	    });
    	    // manual bootstrap process
    	    angular.element(document).ready(function() {
    	        angular.bootstrap(document, ['myApp']);
    	    });
        </script>
    </body>
    
    </html>
    • Note:
      • You should not use the ng-app directive when manually bootstrapping your app
      • You should not mix up the automatic and manual way of bootstrapping your app
      • Define modules, controller, services etc. before manually bootstrapping your app as defined in above example
  44. How to bootstrap your angular app for multiple modules?

    • AngularJS is automatically initialized for one module. But sometimes, it is required to bootstrap for multiple modules and it can be achieved by using two methods:
      • Automatic bootstrap (by combining multiple modules into one module): ou can combine multiple modules into single modules and your angular app will be automatically initialized for newly created module and other modules will act as dependent modules for newly created module. For example, suppose you have two modules: module1 and model2, and you have to initialize your app automatically based on these two modules then you achieve this following way:
       <html>
       
       <head>
           <title>Multiple modules bootstrap</title>
           <script src="lib/angular.js"></script>
           <script>
       	    // module1
       	    var app1 = angular.module("module1", []);
       	    app1.controller("Controller1", function($scope) {
       	        $scope.name = "Shailendra Chauhan";
       	    });
       	    // module2
       	    var app2 = angular.module("module2", []);
       	    app2.controller("Controller2", function($scope) {
       	        $scope.name = "Deepak Chauhan";
       	    });
       	    // module3 dependent on module1 & module2
       	    angular.module("app", ["module1", "module2"]);
           </script>
       </head>
       
       <body>
           <!-- angularjs auto bootstrap process -->
           <div ng-app="app">
               <h1>Multiple modules bootstrap</h1>
               <div ng-controller="Controller2">{{name}}</div>
               <div ng-controller="Controller1"> {{name}}</div>
           </div>
       </body>
       
       </html>
      • Manual bootstrap: You can manually bootstrap your app by using angular.bootstrap() function, for multiple modules. The above example can be rewritten as for manual bootstrap process as given below:
       <html>
       
       <head>
           <title>Multiple modules bootstrap</title>
           <script src="lib/angular.js"></script>
           <script>
               // module1
               var app1 = angular.module("module1", []);
               app1.controller("Controller1", function($scope) {
                   $scope.name = "Shailendra Chauhan";
               });
               // module2
               var app2 = angular.module("module2", []);
               app2.controller("Controller2", function($scope) {
                   $scope.name = "Deepak Chauhan";
               });
               // manual bootstrap process
               angular.element(document).ready(function() {
                   var div1 = document.getElementById('div1');
                   var div2 = document.getElementById('div2');
                   // bootstrap div1 for module1 and module2
                   angular.bootstrap(div1, ['module1', 'module2']);
                   // bootstrap div2 only for module1
                   angular.bootstrap(div2, ['module1']);
               });
           </script>
       </head>
       
       <body>
           <!-- angularjs manual bootstrap process -->
           <div id="div1">
               <h1>Multiple modules bootstrap</h1>
               <div ng-controller="Controller1">{{name}}</div>
               <div ng-controller="Controller2"> {{name}}</div>
           </div>
           <div id="div2">
               <div ng-controller="Controller1">{{name}}</div>
           </div>
       </body>
       
       </html>
  45. What is scope in AngularJS?

    • Scope is a JavaScript object that refers to the application model. It acts as a context for evaluating angular expressions. Basically, it acts as glue between controller and view
    • Scopes are hierarchical in nature and follow the DOM structure of your AngularJS app. AngularJS has two scope objects: $rootScope and $scope
  46. What is $scope and $rootScope

    • $scope: A $scope is a JavaScript object which is used for communication between controller and view. Basically, $scope binds a view (DOM element) to the model and functions defined in a controller
    • $rootScope: The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope
    • For example, suppose you have two controllers: "Ctrl1" and "Ctrl2" as given below:
    <!DOCTYPE html>
    <html>
    
    <body ng-app="myApp">
        <div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px"> 
        	Hello {{msg}}!<br /> 
            Hello {{name}}! (rootScope) 
        </div><br />
        <div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
            Hello {{msg}}!<br /> 
            Hey {{myName}}!<br /> 
            Hi {{name}}! (rootScope) 
        </div>
        <script src="lib/angular.js"></script>
        <script>
    	    var app = angular.module('myApp', []);
    	    app.controller('Ctrl1', function($scope, $rootScope) {
    	        $scope.msg = 'World';
    	        $rootScope.name = 'AngularJS';
    	    });
    	    app.controller('Ctrl2', function($scope, $rootScope) {
    	        $scope.msg = 'Dot Net Tricks';
    	        $scope.myName = $rootScope.name;
    	    });
        </script>
    </body>
    
    </html>
    • Output:
  47. What is scope hierarchy? / What is scope inheritance?

    • The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a child of the $rootScope), so whatever variables you create on $scope within controller, these variables are accessible by the view based on this controller
    • For example, suppose you have two controllers: ParentController and ChildController as given below:
    <html>
    
    <head>
        <script src="lib/angular.js"></script>
        <script>
            var app = angular.module('ScopeChain', []);
            app.controller("parentController", function($scope) {
                $scope.managerName = 'Shailendra Chauhan';
                $scope.$parent.companyName = 'Dot Net Tricks'; //attached to $rootScope
            });
            app.controller("childController", function($scope, $controller) {
                $scope.teamLeadName = 'Deepak Chauhan';
            });
        </script>
    </head>
    
    <body ng-app="ScopeChain">
        <div ng-controller="parentController ">
            <table style="border:2px solid #e37112">
                <caption>Parent Controller</caption>
                <tr>
                    <td>Manager Name</td>
                    <td>{{managerName}}</td>
                </tr>
                <tr>
                    <td>Company Name</td>
                    <td>{{companyName}}</td>
                </tr>
                <tr>
                    <td>
                        <table ng-controller="childController" style="border:2px solid #428bca">
                            <caption>Child Controller</caption>
                            <tr>
                                <td>Team Lead Name</td>
                                <td>{{teamLeadName}}</td>
                            </tr>
                            <tr>
                                <td>Reporting To</td>
                                <td>{{managerName}}</td>
                            </tr>
                            <tr>
                                <td>Company Name</td>
                                <td>{{companyName}}</td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
    </body>
    
    </html>
    • Output:
  48. What is the difference between $scope and scope?

    • The module factory methods like "controller", "directive", "factory", "filter", "service", "animation", "config" and "run" receive arguments through dependency injection (DI). In case of DI, you inject the scope object with the dollar prefix i.e. $scope. The reason is the injected arguments must match to the names of injectable objects followed by dollar ($) prefix
    • For example, you can inject the scope and element objects into a controller as given below:
    module.controller('MyController', function($scope, $element) { // injected arguments });
    • When the methods like directive linker function don’t receive arguments through dependency injection, you just pass the scope object without using dollar prefix i.e. scope. The reason is the passing arguments are received by its caller
    module.directive('myDirective', function() // injected arguments here {
    return {
        // linker function does not use dependency injection
        link: function(scope, el, attrs) {
            // the calling function will passes the three arguments to the linker: scope, element and attributes, in the same order
        }
    };
    });
    • In the case of non-dependency injected arguments, you can give the name of injected objects as you wish. The above code can be re-written as:
    module.directive("myDirective", function() {
        return {
            link: function(s, e, a) {
                // s == scope
                // e == element
    			// a == attributes
            }
        };
    });
    • In short, in case of DI the scope object is received as $scope while in case of non-DI scope object is received as scope or with any name
  49. How AngularJS is compiled?

    • Angular's HTML compiler allows you to teach the browser new HTML syntax. The compiler allows you to attach new behaviors or attributes to any HTML element. Angular calls these behaviors as directives
    • AngularJS compilation process takes place in the web browser; no server side or pre-compilation step is involved. Angular uses $compiler service to compile your angular HTML page. The angular' compilation process begins after your HTML page (static DOM) is fully loaded. It happens in two phases:
      1. Compile: It traverse the DOM and collect all of the directives. The result is a linking function
      2. Link: It combines the directives with a scope and produces a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model
    • The concept of compile and link comes from C language, where you first compile the code and then link it to actually execute it. The process is very much similar in AngularJS as well
  50. How AngularJS compilation is different from other JavaScript frameworks?

    • If you have worked on templates in other java script framework/library like Backbone and jQuery, they process the template as a string and result as a string. You have to dumped this result string into the DOM where you wanted it with innerHTML()
    • AngularJS process the template in another way. It directly works on HTML DOM rather than strings and manipulates it as required. It uses two way data-binding between model and view to sync your data
  51. How Directives are compiled?

    • It is important to note that Angular operates on DOM nodes rather than strings. Usually, you don't notice this because when an html page loads, the web browser parses HTML into the DOM automatically
    • HTML compilation happens in three phases:
      1. The $compile traverses the DOM and looks for directives. For each directive it finds, it adds it to a list of directives
      2. Once the entire DOM has been traversed, it will sort that list of directives by their priority. Then, each directive’s own compile function is executed, giving each directive the chance to modify the DOM itself. Each compile function returns a linking function, which is then composed into a combined linking function and returned
      3. $compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the individual directives, registering listeners on the elements and setting up $watch with the scope as each directive is configured to do
    • The pseudo code for the above process is given below:
    var $compile = ...; // injected into your code
    var scope = ...;
    var parent = ...; // DOM element where the compiled template can be appended
    var html = '<div ng-bind="exp"></div>';
    
    // Step 1: parse HTML into DOM element
    var template = angular.element(html);
    
    // Step 2: compile the template
    var linkFn = $compile(template);
    
    // Step 3: link the compiled template with the scope.
    var element = linkFn(scope);
    
    // Step 4: Append to DOM (optional)
    parent.appendChild(element);
  52. What are Compile, Pre, and Post linking in AngularJS?

    • Compile: This compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together
    • Use the compile function to change the original DOM (template element) before AngularJS creates an instance of it and before a scope is created
    • Post-Link: This is executed after the child elements are linked. It is safe to do DOM transformation in the post- linking function
    • Use the post-link function to execute logic, knowing that all child elements have been compiled and all pre-link and post-link functions of child elements have been executed
    • Pre-Link: This is executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking
    • Use the pre-link function to implement logic that runs when AngularJS has already compiled the child elements, but before any of the child element's post-link functions have been called
    <html>
    
    <head>
        <title>Compile vs Link</title>
        <script src="lib/angular.js"></script>
        <script type="text/javascript">
    	    var app = angular.module('app', []);
    
    	    function createDirective(name) {
    	        return function() {
    	            return {
    	                restrict: 'E',
    	                compile: function(tElem, tAttrs) {
    	                    console.log(name + ': compile');
    	                    return {
    	                        pre: function(scope, iElem, attrs) {
    	                            console.log(name + ': pre link');
    	                        },
    	                        post: function(scope, iElem, attrs) {
    	                            console.log(name + ': post link');
    	                        }
    	                    }
    	                }
    	            }
    	        }
    	    }
    	    app.directive('levelOne', createDirective('level-One'));
    	    app.directive('levelTwo', createDirective('level-Two'));
    	    app.directive('levelThree', createDirective('level-Three'));
        </script>
    </head>
    
    <body ng-app="app">
        <level-one>
            <level-two>
                <level-three> 
                	Hello {{name}}
                </level-three>
            </level-two>
        </level-one>
    </body>
    
    </html>
    • Output:
  53. What directives are used to show and hide HTML elements in AngularJS?

    • ng-show and ng-hide directives are used to show and hide HTML elements in the AngularJS based on an expression. When the expression is true for ng-show or ng-hide, HTML element(s) are shown or hidden from the page. When the expression is false for ng-show or ng-hide, HTML element(s) are hidden or shown on the page
    <div ng-controller="MyCtrl">
        <div ng-show="data.isShow">ng-show Visible</div>
        <div ng-hide="data.isHide">ng-hide Invisible</div>
    </div>
    <script>
    	var app = angular.module("app", []);
    	app.controller("MyCtrl", function($scope) {
    	    $scope.data = {};
    	    $scope.data.isShow = true;
    	    $scope.data.isHide = true;
    	});
    </script>
  54. Explain directives ng-if, ng-switch and ng-repeat?

    • ng-if: This directive can add / remove HTML elements from the DOM based on an expression. If the expression is true, it add HTML elements to DOM, otherwise HTML elements are removed from the DOM
    <div ng-controller="MyCtrl">
        <div ng-if="data.isVisible">ng-if Visible</div>
    </div>
    <script>
    	var app = angular.module("app", []);
    	app.controller("MyCtrl", function($scope) {
    	    $scope.data = {};
    	    $scope.data.isVisible = true;
    	});
    </script>
    • ng-switch: This directive can add / remove HTML elements from the DOM conditionally based on scope expression
    <div ng-controller="MyCtrl">
        <div ng-switch on="data.case">
            <div ng-switch-when="1">Shown when case is 1</div>
            <div ng-switch-when="2">Shown when case is 2</div>
            <div ng-switch-default>Shown when case is anything else than 1 and 2</div>
        </div>
    </div>
    <script>
    	var app = angular.module("app", []);
    	app.controller("MyCtrl", function($scope) {
    	    $scope.data = {};
    	    $scope.data.case = true;
    	});
    </script>
    • ng-repeat: This directive is used to iterate over a collection of items and generate HTML from it
    <div ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="name in names">{{ name }}</li>
        </ul>
    </div>
    <script>
    	var app = angular.module("app", []);
    	app.controller("MyCtrl", function($scope) {
    	    $scope.names = ['Shailendra', 'Deepak', 'Kamal'];
    	});
    </script>
  55. What are ng-repeat special variables?

    • The ng-repeat directive has a set of special variables which you are useful while iterating the collection. These variables are as follows:
      • $index
      • $first
      • $middle
      • $last
    <html>
    
    <head>
        <script src="lib/angular.js"></script>
        <script>
    	    var app = angular.module("app", []);
    	    app.controller("ctrl", function($scope) {
    	        $scope.friends = [{
    	            name: 'shailendra',
    	            gender: 'boy'
    	        }, {
    	            name: 'kiran',
    	            gender: 'girl'
    	        }, {
    	            name: 'deepak',
    	            gender: 'boy'
    	        }, {
    	            name: 'pooja',
    	            gender: 'girl'
    	        }];
    	    });
        </script>
    </head>
    
    <body ng-app="app">
        <div ng-controller="ctrl">
            <ul class="example-animate-container">
                <li ng-repeat="friend in friends">
                    <div>
                        [{{$index + 1}}] {{friend.name}} is a {{friend.gender}}.
                        <span ng-if="$first"><strong>(first element found)</strong></span>
                        <span ng-if="$middle"><strong>(middle element found)</strong> </span>
    					<span ng-if="$last"><strong>(last element found)</strong></span>
                    </div>
                </li>
            </ul>
        </div>
    </body>
    
    </html>
    • Output:
    • The $index contains the index of the element being iterated. The $first, $middle and $last returns a boolean value depending on whether the current item is the first, middle or last element in the collection being iterated
  56. What are Templates in AngularJS?

    • AngularJS templates are just plain old HTML that contains Angular-specific elements and attributes. AngularJS used these templates to show information from the model and controller
    • Creating an AngularJS template:
    <html ng-app>
    
    <!-- body tag with ngController directive -->
    <body ng-controller="MyController">
        <input ng-model="txtName" value="shailendra" />
        <!-- button tag with ng-click directive & string expression 'btnText' wrapped in "{{ }}" markup -->
        <button ng-click="changeName()">{{btnText}}</button>
        <script src="angular.js"></script>
    </body>
    
    </html>
  57. What is ng-include and when to use it?

    • ng-include is a directive which is used to include external HTML fragments from other files into the view's HTML template
    • For example, index.html file can be added inside the div element by using ng-include directive as an attribute
    <div ng-controller="MyCtrl">
        <div ng-include="'index.html'"></div>
    </div>
    • ng-include directive is limited to load HTML fragments file from same domain but it doesn’t work for cross-domain i.e. it can’t load the HTML fragments file from different domains
  58. What angular components can be defined within AngularJS templates?

    • AngularJS templates can have following angular elements and attributes:
      1. Directive
      2. Angular Markup ({{ }})
      3. Filters
      4. Form Controls
  59. What is data binding in AngularJS?

    • AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e. the sections of code which is included in many places with little or no alteration). Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the synchronization of data between model and view
  60. Explain Two-way and One-way data binding in AngularJS?

    • Two-way data binding: It is used to synchronize the data between model and view. It means, any change in model will update the view and vice versa. ng-model directive is used for two-way data binding
    • One-way data binding: This binding is introduced in Angular 1.3. An expression that starts with double colon (::), is considered a one-time expression i.e. one-way binding
    • Two-Way and One-Way data binding Example
    <div ng-controller="MyCtrl">
        <label>Name (two-way binding):<input type="text" ng-model="name" /></label>
        <strong>Your name (one-way binding):</strong> {{::name}}<br />
        <strong>Your name (normal binding):</strong> {{name}}
    </div>
    <script>
    	var app = angular.module('app', []);
    	app.controller("MyCtrl", function($scope) {
    	    $scope.name = "Shailendra Chauhan"
    	})
    </script>
  61. What is issue with two-way data binding? / Why one-way data binding is introduced?

    • In order to make data-binding possible, Angular uses $watch APIs to observe model changes on the scope. Angular registered watchers for each variable on scope to observe the change in its value. If the value, of variable on scope is changed then the view gets updated automatically
    • This automatic change happens because of $digest cycle is triggered. Hence, Angular processes all registered watchers on the current scope and its children and checks for model changes and calls dedicated watch listeners until the model is stabilized and no more listeners are fired. Once the $digest loop finishes the execution, the browser re-renders the DOM and reflects the changes
    • By default, every variable on a scope is observed by the angular. In this way, unnecessary variable are also observed by the angular that is time consuming and as a result page is becoming slow
    • Hence to avoid unnecessary observing of variables on scope object, angular introduced one-way data binding
  62. How AngularJS handle data binding?

    • AngularJS handle data-binding mechanism with the help of three powerful functions: $watch(), $digest() and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest() functions for you, but in some cases you may have to call these functions yourself to update new values
  63. What is the difference between $watch, $digest and $apply?

    • $watch(): This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters
    $watch(watchExpression, listener, [objectEquality])
    <html>
    
    <head>
        <title>AngularJS Watch</title>
        <script src="lib/angular.js"></script>
        <script>
    	    var myapp = angular.module("myapp", []);
    	    var myController = myapp.controller("myController", function($scope) {
    	        $scope.name = 'dotnet-tricks.com';
    	        $scope.counter = 0;
    	        // watching change in name value
    	        $scope.$watch('name', function(newValue, oldValue) {
    	            $scope.counter = $scope.counter + 1;
    	        });
    	    });
        </script>
    </head>
    
    <body ng-app="myapp" ng-controller="myController">
        <input type="text" ng-model="name" />
        <br /><br /> 
        Counter: {{counter}}
    </body>
    
    </html>
    • $digest(): This function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with the new value and the old value
    $digest()
    • The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself
    <html>
    
    <head>
        <script src="lib/jquery-1.11.1.js"></script>
        <script src="lib/angular.js"></script>
    </head>
    
    <body ng-app="app">
        <div ng-controller="Ctrl">
            <button class="digest">Digest my scope!</button><br />
            <h2>obj value : {{obj.value}}</h2>
        </div>
        <script>
    	    var app = angular.module('app', []);
    	    app.controller('Ctrl', function($scope) {
    	        $scope.obj = {
    	            value: 1
    	        };
    	        $('.digest').click(function() {
    	            console.log("digest clicked!");
    	            console.log($scope.obj.value++);
    	            //update value
    	            $scope.$digest();
    	        });
    	    });
        </script>
    </body>
    
    </html>
    • $apply(): Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated
    $apply([exp])
    • Example:
    <html>
    
    <head>
        <title>AngularJS Apply</title>
        <script src="lib/angular.js"></script>
        <script>
    	    var myapp = angular.module("myapp", []);
    	    var myController = myapp.controller("myController", function($scope) {
    	        $scope.datetime = new Date();
    	        $scope.updateTime = function() {
    	            $scope.datetime = new Date();
    	        };
    	        // outside angular context
    	        document.getElementById("updateTimeButton").addEventListener('click', function() {
    	            // update the value
    	            $scope.$apply(function() {
    	                console.log("update time clicked");
    	                $scope.datetime = new Date();
    	                console.log($scope.datetime);
    	            });
    	        });
    	    });
        </script>
    </head>
    
    <body ng-app="myapp" ng-controller="myController">
        <button ng-click="updateTime()">Update time - ng-click</button>
        <button id="updateTimeButton">Update time</button><br /> 
        {{datetime | date:'yyyy-MM-dd HH:mm:ss'}}
    </body>
    
    </html>
  64. Which one is fast between $digest and $apply?

    • $digest() is faster than $apply(), since $apply() triggers watchers on the entire scope chain i.e. on the current scope and its parents or children (if it has) while $digest() triggers watchers on the current scope and its children(if it has)
  65. Which one handles exception automatically between $digest and $apply?

    • When error occurs in one of the watchers, $digest() cannot handled errors via $exceptionHandler service, In this case you have to handle exception yourself
    • While $apply() uses try catch block internally to handle errors and if error occurs in one of the watchers then it passes errors to $exceptionHandler service
    • Pseudo-Code of $apply():
    function $apply(expr) {
        try {
            return $eval(expr);
        } catch (e) {
            $exceptionHandler(e);
        } finally {
            $root.$digest();
        }
    }
  66. Explain $watch(), $watchgroup() and $watchCollection() functions of scope?

    • $watch: This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters
    $watch(watchExpression, listener, [objectEquality])
    • Here, watchExpression is the expression in the scope to watch. This expression is called on every $digest() and returns the value that is being watched
    • The listener defines a function that is called when the value of the watchExpression changes to a new value. If the watchExpression is not changed then listener will not be called
    • The objectEquality is a boolean type which is used for comparing the objects for equality using angular.equals instead of comparing for reference equality
    scope.name = 'shailendra';
    scope.counter = 0;
    scope.$watch('name', function(newVal, oldVal) {
        scope.counter = scope.counter + 1;
    });
    • $watchgroup: This function is introduced in Angular1.3. This works the same as $watch() function except that the first parameter is an array of expressions to watch
    $watchGroup(watchExpression, listener)
    • The listener is passed as an array with the new and old values for the watched variables. The listener is called whenever any expression in the watchExpressions array changes
    $scope.teamScore = 0;
    $scope.time = 0;
    $scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
        if (newVal[0] > 20) {
            $scope.matchStatus = 'win';
        } else if (newVal[1] > 60) {
            $scope.matchStatus = 'times up';
        }
    });
    • $watchCollection: This function is used to watch the properties of an object and fires whenever any of the properties change. It takes an object as the first parameter and watches the properties of the object
    $watchCollection(obj, listener)
    • The listener is called whenever anything within the obj has been changed
    $scope.names = ['shailendra', 'deepak', 'mohit', 'kapil'];
    $scope.dataCount = 4;
    $scope.$watchCollection('names', function(newVal, oldVal) {
        $scope.dataCount = newVal.length;
    });
  67. Explain AngularJS scope life-cycle?

    • Scope data goes through a life cycle when the angular app is loaded into the browser. Understanding the scope life cycle will help you to understand the interaction between scope and other AngularJS components
    • The scope data goes through the following life cycle phases:
      1. Creation: This phase initialized the scope. The root scope is created by the $injector when the application is bootstrapped. During template linking, some directives create new child scopes. A digest loop is also created in this phase that interacts with the browser event loop. This digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions
      2. Watcher registration: This phase registers watches for values on the scope that are represented in the template. These watches propagate model changes automatically to the DOM elements. You can also register your own watch functions on a scope value by using the $watch() function
      3. Model mutation: This phase occurs when data in the scope changes. When you make the changes in your angular app code, the scope function $apply() updates the model and calls the $digest() function to update the DOM elements and registered watches. When you do the changes to scope inside your angular code like within controllers or services, angular internally call $apply() function for you. But when you do the changes to the scope outside the angular code, you have to call $apply() function explicitly on the scope to force the model and DOM to be updated correctly
      4. Mutation observation: This phase occurs when the $digest() function is executed by the digest loop at the end of $apply() call. When $digest() function executes, it evaluates all watches for model changes. If a value has been changed, $digest() calls the $watch listener and updates the DOM elements
      5. Scope destruction: This phase occurs when child scopes are no longer needed and these scopes are removed from the browser’s memory by using $destroy() function. It is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This stop propagation of $digest calls into the child scopes and allow the memory to be reclaimed by the browser garbage collector
  68. Explain digest life-cycle in AngularJS?

    • The digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions
    • The $digest loop is fired when the browser receives an event that can be managed by the angular context. This loop is made up of two smaller loops. One processes the $evalAsync queue and the other one processes the $watch list
    • The $digest loop keeps iterating until the $evalAsync queue is empty and the $watch list does not detect any changes in the model
    • The $evalAsync queue contains those tasks which are scheduled by $evalAsync() function from a directive or controller
    • The $watch list contains watches correspondence to each DOM element which is bound to the $scope object. These watches are resolved in the $digest loop through a process called dirty checking. The dirty checking is a process which checks whether a value has changed, if the value has changed, it set the $scope as dirty. If the $scope is dirty, another $digest loop is triggered
    • When you do the changes to the scope outside the angular context, you have to call $apply() function explicitly on the scope to trigger $digest cycle immediately
  69. When to use $destroy() function of scope?

    • $destroy(): This function permanently detached the current scope with all of its children from the parent scope. This is required when child scopes are no longer needed. Hence, $destroy() function is called to remove these scopes from the browser’s memory
    • When $destroy() is called all the watchers and listeners get removed and the object which represented the scope becomes eligible for garbage collection
  70. What is difference between $evalAsync and $timeout?

    • $evalAsync: This executes the expression on the current scope on later time. The $evalAsync makes no guarantees as to when the expression will be executed, only that:
      1. If code is queued using $evalAsync from a directive, it will run after the DOM has been manipulated by Angular, but before the browser renders
      2. If code is queued using $evalAsync from a controller, it will run before the DOM has been manipulated by Angular and before the browser renders
    • $timeout: This also executes the expression on the current scope on later time. When the code is queued using $timeout, it will run after the DOM has been manipulated by Angular and after the browser renders which may cause flicker in some cases
  71. What is the difference between $watch and $observe?

    • $watch is a method on the scope object which is used to watch expressions. The expression can be either strings or functions. It can be called wherever you have access to scope (a controller or a directive linking function)
    • $observe is a method on the attrs object which is only used to observe the value change of a DOM attribute. It is only used inside directives
    • Note: All $observes and $watches are checked on every digest cycle
  72. What is the difference between $parse and $eval?

    • $parse and $eval both operate on angular expressions i.e. {{ expression }}
    • $eval is a scope method which executes an expression on the current scope and returns the result
    scope.a = 1;
    scope.b = 2;
    scope.$eval('a+b');  // 3
    • $parse is an Angular service which converts an expression into a function. Then function can be invoked and passed a context (usually scope) in order to retrieve the expression's value
    <div my-attr="obj.name" my-directive>
        Google
    </div>
    <script type="text/javascript">
        myApp.directive('myDirective', function($parse, $log) {
            return function(scope, el, attrs) {
                // parse the "my-attr" attribute value into a function
                var myFn = $parse(attrs.myAttr);
                // "myFn" is now a function which can be invoked to get the expression's value;
                // the following line logs the value of obj.name on scope:
                $log.log(myFn(scope)); // dotnet-tricks.com
                el.bind('click', function() {
                    // "myFn.assign" is also a function; it can be invoked to
                    // update the expresssion value
                    myFn.assign(scope, "New name");
                    scope.$apply();
                })
            }
        });
    </script>
    • Also, if the expression is assignable then the returned function will have an assign property. The assign property is a function that can be used to change the expression's value on the given context
  73. What is Isolate Scope and why it is required?

    • By default, directives have access to the parent scope in AngularJS apps. Hence, you can write your custom directive code based on parent scope. If the parent scope changes at all the directive is no longer useful
    angular.module('mydirective').directive('sharedScope', function() {
        return {
            template: 'Name: {{emp.name}} Address: {{emp.address}}'
        };
    });
    • The shared scope allows the parent scope to flow down into the directive but the Isolate scope doesn’t allow the parent scope to flow down into the directive
    • Creating Isolate Scope: You can isolate the scope in a directive by adding a scope property into the directive as given below:
    angular.module('mydirective').directive('sharedScope', function() {
        return {
            scope: {},
            template: 'Name: {{emp.name}} Address: {{emp.address}}'
        };
    });
  74. Does AngularJS support MVC?

    • AngularJS is a MVC framework. It does not implement MVC in the traditional way, but rather something closer to MVVM Model-View-ViewModel)
  75. What is Model in AngularJS?

    • Models are plain old JavaScript objects that represent data used by your app. Models are also used to represent your app's current state
  76. What is ViewModel in AngularJS? - A viewmodel is an object that provides specific data and methods to maintain specific views. Basically, it is a $scope object which lives within your AngularJS app's controller. A viewmodel is associated with a HTML element with the ng-model and ng-bind directives

  77. What is Controller in AngularJS? - The controller defines the actual behavior of your app. It contains business logic for the view and connects the model to view with the help of $scope. A controller is associated with a HTML element with the ng-controller directive - Creating Controller: html <script type="text/javascript"> // Defining main controller app.controller('mainController', function($scope) { // Defining book viewmodel $scope.book = { id: 1, name: 'AngularJS Interview Questions and Answers', author: 'Shailendra Chauhan', }; }); </script> - Using Controller: html <div ng-controller="mainController"> Id: <span ng-bind="book.id"></span> <br /> Name: <input type="text" ng-model="book.name" /> <br /> Author: <input type="text" ng-model="book.author" /> </div>

  78. How to share information between controllers in AngularJS? / What are the ways to communicate between controllers in AngularJS? - There are various different ways to share data between controllers in an AngularJS app. The most commonly used are Scope, Service, Factory and Providers

  79. What is $emit, $broadcast and $on in AngularJS? - AngularJS provides $on, $emit, and $broadcast services for event-based communication between controllers - $emit: It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it ```html

<head>
    <title>Broadcasting</title>
    <script src="lib/angular.js"></script>
    <script>
        var app = angular.module('app', []);
        app.controller("firstCtrl", function($scope) {
            $scope.$on('eventName', function(event, args) {
                $scope.message = args.message;
                console.log($scope.message);
            });
        });
        app.controller("secondCtrl", function($scope) {
            $scope.handleClick = function(msg) {
                $scope.$emit('eventName', {
                    message: msg
                });
            };
        });
    </script>
</head>

<body ng-app="app">
    <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
        <h1>Parent Controller</h1>
        <p>Emit Message : {{message}}</p>
        <br />
        <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
            <h1>Child Controller</h1>
            <input ng-model="msg">
            <button ng-click="handleClick(msg);">Emit</button>
        </div>
    </div>
</body>

</html>
```
- Output: 
![](http://i1175.photobucket.com/albums/r629/bminhz/Screen%20Shot%202015-11-17%20at%2010.54.16%20AM_zpsdfat3p22.png)
![](http://i1175.photobucket.com/albums/r629/bminhz/Screen%20Shot%202015-11-17%20at%2010.54.23%20AM_zpszdrx7dw8.png)
- **`$broadcast`**: It dispatches an event name downwards to all child scopes (and their children) and notify to the registered `$rootScope.Scope` listeners. The event life cycle starts at the scope on which `$broadcast` was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event **CANNOT** be canceled
```html
<!DOCTYPE html>
<html>

<head>
    <title>Broadcasting</title>
    <script src="lib/angular.js"></script>
    <script>
        var app = angular.module('app', []);
        app.controller("firstCtrl", function($scope) {
            $scope.handleClick = function(msg) {
                $scope.$broadcast('eventName', {
                    message: msg
                });
            };
        });
        app.controller("secondCtrl", function($scope) {
            $scope.$on('eventName', function(event, args) {
                $scope.message = args.message;
                console.log($scope.message);
            });
        });
    </script>
</head>

<body ng-app="app">
    <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
        <h1>Parent Controller</h1>
        <input ng-model="msg">
        <button ng-click="handleClick(msg);">Broadcast</button>
        <br />
        <br />
        <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
            <h1>Child Controller</h1>
            <p>Broadcast Message : {{message}}</p>
        </div>
    </div>
</body>

</html>
```
- Output:
![](http://i1175.photobucket.com/albums/r629/bminhz/Screen%20Shot%202015-11-17%20at%2010.54.33%20AM_zps9ornrlbp.png)
- **`$on`**: It listen on events of a given type. It can catch the event dispatched by `$broadcast` and `$emit`
- **Note**: If there is no parent-child relation between your scopes you can inject `$rootScope` into the controller and broadcast the event to all child scopes but you cannot emit your event. You can emit your event only when you have parent-child relation and event propagation is initiated by child. However, `$emit` can fire an event only for all `$rootScope.$on` listeners
  1. What is View in AngularJS? - The view is responsible for presenting your models data to end user. Typically it is the HTML markup which exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings

  2. How to apply validation in AngularJS? - AngularJS provides you built-in validation directives to validate form client side. This makes your life pretty easy to handle client-side form validations without adding a lot of extra effort. AngularJS form validations are based on the HTML5 form validators - AngularJS directives for form validation: Here is a list of AngularJS directive which can be applied on an input field to validate its value html <input type="text" ng-model="{ string }" [name="{ string }"] [ng-required="{ boolean }"] [ng-minlength="{ number }"] [ng-maxlength="{ number }"] [ng-pattern="{ string }"] [ng-change="{ string }"]> </input>

  3. How to do custom form validation in AngularJS? - AngularJS allows you to create your own custom validation directives. For example, you have to compare password and confirm password fields. To achieve this task, you have to make a custom directive that will be fired whenever the password or confirm password changes - Creating custom directive to compare password and confirm password fields js // Defining module var myapp = angular.module('myapp', []); // Creating custom directive myapp.directive('ngCompare', function() { return { require: 'ngModel', link: function(scope, currentEl, attrs, ctrl) { var comparefield = document.getElementsByName(attrs.ngCompare)[0]; //getting first element compareEl = angular.element(comparefield); //current field key up currentEl.on('keyup', function() { if (compareEl.val() != "") { var isMatch = currentEl.val() === compareEl.val(); ctrl.$setValidity('compare', isMatch); scope.$digest(); } }); //Element to compare field key up compareEl.on('keyup', function() { if (currentEl.val() != "") { var isMatch = currentEl.val() === compareEl.val(); ctrl.$setValidity('compare', isMatch); scope.$digest(); } }); } } }); - Using the above created custom directive ```html

    Password

    Your password is required.

    Confirm Password

    Confirm password doesn’t match.

</form>
```
  1. What are different Angular form properties? - Angular provides properties on form which help you to get information about a form or its inputs and to validate them - $valid: It is a boolean property that tells whether the form or it's inputs are valid or not. If all containing form and controls are valid, then it will be true, otherwise it will be false js // Syntax formName.$valid formName.inputFieldName.$valid - $invalid: It is a boolean property that tells whether the form or it's inputs are invalid or not. If at least one containing form and control is invalid then it will be true, otherwise it will be false js // Syntax formName.$invalid formName.inputFieldName.$invalid - $pristine: It is a boolean property that tells whether the form or it's inputs are unmodified by the user or not. If the form or its inputs are unmodified by the user, then it will be true, otherwise it will be false js // Syntax formName.inputFieldName.$pristine - $dirty: It is a boolean property that is actually just reverse of pristine i.e. it tells whether the form or it's inputs are modified by the user or not. If the form or its inputs are modified by the user, then it will be true, otherwise it will be false js // Syntax formName.$dirty formName.inputFieldName.$dirty - $error: This is an object hash which contains references to all invalid controls or forms. It has all errors as keys: where keys are validation tokens (such as required, url or email) and values are arrays of controls or forms that are invalid with given error. For a control, if a validation fails then it will be true, otherwise it will be false js // Syntax formName.$error formName.inputFieldName.$error

  2. What are different states of a form in AngularJS? - The AngularJS form goes to the following states, starting from the form rendering and when the user has finished the filling of form

    • State 1 (pristine and invalid): When the form is first time rendered and the user has not interacted with the form yet
    • State 2 (dirty and invalid): User has interacted with the form, but form validity has not been satisfied, yet
    • State 3 (dirty and valid): User has finished the filling of form and the entire form validations has been satisfied
  3. What is Service in AngularJS? - A service is a reusable singleton object which is used to organize and share code across your app. A service can be injected into controllers, filters, directives - AngularJS offers several built-in services (like $http, $provide, $resource, $window, $parse) which always start with $ sign

  4. What are different ways to create service in AngularJS? - There are 5 ways to create a service as given below:

    1. Service
    2. Factory
    3. Provider
    4. Value
    5. Constant
  5. What is the difference between Factory, Service and Provider? - Factory: A factory is a simple function which allows you to add some logic before creating the object. It returns the created object js // Define a factory using factory() function app.factory('MyFactory', function() { var serviceObj = {}; serviceObj.function1 = function() { // TO DO: }; serviceObj.function2 = function() { // TO DO: }; return serviceObj; }); - When to use: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function - Service: A service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything js // Define a service using service() function app.service('MyService', function() { this.function1 = function() { // TO DO: }; this.function2 = function() { // TO DO: }; }); - When to use: It is a singleton object. Use it when you need to share a single object across the application. For example, authenticated user details - Provider: A provider is used to create a configurable service object. It returns value by using $get() function js // Define a provider using provider() function app.provider('configurable', function() { var privateName = ''; this.setName = function(newName) { privateName = newName; }; this.$get = function() { return { name: privateName }; }; }); // Configuring provider using config() function app.config(function(configurableService) { configurableService.setName('www.dotnet-tricks.com'); }); - When to use: When you need to provide module-wise configuration for your service object before making it available ```html

<head>
    <title>AngularJS Service, Factory and Providers</title>
    <script src="lib/angular.js"></script>
</head>

<body>
    <div class="container" style="padding-top:20px;">
        <div ng-app="myApp" ng-controller="myController">
            <p>From Service: {{serviceName}}</p>
            <p>From Factory: {{factoryName}}</p>
            <p>From Provider: {{providerName}}</p>
        </div>
    </div>
    <script>
    // Defining module
    var app = angular.module('myApp', []);
    // Defining service
    app.service('myService', function() {
        this.name = '';
        this.setName = function(newName) {
            this.name = newName;
            return this.name;
        };
    });
    // Defining factory
    app.factory('myFactory', function() {
        var serviceObj = {};
        serviceObj.name = '';
        serviceObj.setName = function(newName) {
            serviceObj.name = newName;
        };
        return serviceObj;
    });
    // Defining provider
    app.provider('configurable', function() {
        var privateName = '';
        this.setName = function(newName) {
            privateName = newName;
        };
        this.$get = function() {
            return {
                name: privateName
            };
        };
    });
    // Configuring provider
    app.config(function(configurableProvider) {
        configurableProvider.setName("Saksham Chauhan");
    });
    // Defining controller
    app.controller('myController', function($scope, myService, myFactory, configurable) {
        $scope.serviceName = myService.setName("Saksham Chauhan");
        myFactory.setName("Saksham Chauhan");
        $scope.factoryName = myFactory.name;
        $scope.providerName = configurable.name;
    });
    </script>
</body>

</html>
```
- Output: 
```text
From Service: Saksham Chauhan
From Factory: Saksham Chauhan
From Provider: Saksham Chauhan
```
  1. What is difference between value and constant? - Value and Constant are simple objects which are used to share data globally with in a module - Value: A value can be a number, string, date-time, array or object. You can also register a function as a value. Values are typically used as configuration which is injected into factories, services or controllers js // Define module var app = angular.module('app', []); // Define value app.value("numberValue", 100); app.value("stringValue ", "Google"); app.value("objectValue", { name: "Google", totalUsers: 120000 }); - Constant: A constant is like as value. The difference between a value and a constant service is that constant service can be injected into a module configuration function i.e. config() but value service cannot be js // Define module var app = angular.module('app', []); // Define constant app.constant("mynumberValue", 200); app.constant("mystringValue", "webgeekschool.com"); // Module configuration function app.config(function(mynumberValue) { //here value objects can't be injected console.log("Before:" + mynumberValue); mynumberValue = "New Angular Constant Service"; console.log("After:" + mynumberValue); });

  2. What is the difference between $http and $resource? - $http service is a core Angular service which allows you to make AJAX requests by using GET, HEAD, POST, PUT, DELETE, JSONP and PATCH methods. It is very much like the $.ajax() method in jQuery. It can be used with RESTful and Non-RESTful server-side data sources - $http is good for quick retrieval of server-side data that doesn’t really need any specific structure or complex behaviors - $resource warps $http and allows you to interact with RESTful server-side data sources. It requires the ngResource module to be installed which exist in angular-resource.js - $http is good for retrieval of RESTful server-side data sources that might need any specific structure or complex behaviors

  3. What methods $http service support? - The $http service supports the following methods:

    1. $http.get()
    2. $http.head()
    3. $http.post()
    4. $http.put()
    5. $http.delete()
    6. $http.jsonp()
    7. $http.patch()
  4. How to enable caching in $http service? - You can enable caching in $http service by setting configuration property cache to true. When cache is enabled, $http service stores the response from the server in local cache. In this way, next time the response will be served from the cache without sending request to server js $http.get("http://server/myserviceapi", { cache: true }).sucess(function() { // TO DO: });

  5. What methods $resource service object support? - The $resource service object supports the following methods:

    1. get()
    2. query()
    3. save()
    4. remove()
    5. delete()
  6. What is $q service and when to use it? - $q is a service that helps you to run functions asynchronously, and use their return values when they have done processing - $q service is said to be inspired by Chris Kowal's Q library which allow users to monitor asynchronous progress by providing a "promise" as a return from a call - It is good when you need to process a number of asynchronous activities simultaneously. The $q.all() function lets you trigger several callbacks at the same time, and use a single then function to join them all together js var first = $http.get("/app/data/first.json"), second = $http.get("/app/data/second.json"), third = $http.get("/app/data/third.json"); $q.all([first, second, third]).then(function(result) { var tmp = []; angular.forEach(result, function(response) { tmp.push(response.data); }); return tmp; }).then(function(tmpResult) { $scope.combinedResult = tmpResult.join(", "); });

  7. What is the difference between Kris Kowal's Q and $q? - There are two main differences between Kris Kowal's Q and $q:

    1. $q is integrated with the $rootScope.Scope scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI
    2. Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks
  8. What is Restangular? - Restangular is an Angular service specifically designed simply to fetch data from the rest of the world. To use Restangular you need to link the restangular.js file and include restangular resource as a dependency within your angular app js var app = angular.module('myApp', ['restangular']); app.controller('MainController', function($scope, Restangular) { // TO DO: });

  9. What are the advantages of Restangular over $resource and $http? - Restangular has several features that distinguish it from $resource:

    1. It uses promises
    2. You can use this in $routeProvider.resolve
    3. It doesn't have all those $resource bugs like trailing slashes, additional: in the URL, escaping information, expecting only arrays for getting lists, etc
    4. It supports all HTTP methods
    5. It supports ETag out of the box
    6. It supports self-linking elements if you receive from the server some item that has a link to itself, you can use that to query the server instead of writing the URL manually
    7. You don't have to create one $resource object per request
    8. You don't have to write or remember ANY URL like $resource. You just write the name of the resource you want to fetch and that's it
    9. It supports nested RESTful resources
    10. Restangular lets you create your own methods
    11. Support for wrapped responses
  10. What is difference between $window and window in AngularJS? - $window is an Angular service which reference to the browser's window object. The window object is globally available in JavaScript; it causes testability problems, because it is a global variable. Angular refer to it through the $window service, so that it can be overridden, removed or mocked for testing html <script> var app = angular.module('windowExample', []); app.controller('ExampleController', function($scope, $window) { $scope.greeting = 'Hello, World!'; $scope.doGreeting = function(greeting) { $window.alert(greeting); }; }); </script> <div ng-app="windowExample" ng-controller="ExampleController"> <input type="text" ng-model="greeting" /> <button ng-click="doGreeting(greeting)">ALERT</button> </div>

  11. What is difference between $document and window.document in AngularJS? - $document is an Angular service which reference to the browser's window.document object ```html <script> var app = angular.module('documentExample', []); app.controller('ExampleController', ['$scope', '$document', function($scope, $document) { $scope.title = $document[0].title; $scope.windowTitle = angular.element(window.document)[0].title; }]); </script>

    $document title:

    window.document title:

</div>
```
  1. What is difference between $timeout and window.setTimeout in AngularJS? - $timeout is an Angular service which wraps the browser's window.setTimeout() function into a try/catch block and delegates any exceptions to $exceptionHandler service. It is used to call a JavaScript function after a given time delay. The $timeout service only schedules a single call to the function ```js var app = angular.module("app", []); app.controller("MyController", function($scope, $timeout) { $timeout(callAtTimeout, 1000); });
function callAtTimeout() {
    console.log("Timeout occurred");
}
```
  1. What is difference between $interval and window. setInterval in AngularJS? - $interval is an Angular service which wraps the browser's window.setInterval() function. It is also used to call a JavaScript function repeatedly within a time interval ```js var app = angular.module("app", []); app.controller("MyController", function($scope, $interval) { $interval(callAtInterval, 3000); });
function callAtInterval() {
    console.log("Interval occurred");
}
```
  1. What is Routing in AngularJS? - AngularJS Routing helps you to divide your app into multiple views and bind different views to controllers. The magic of Routing is taken care by an AngularJS service $routeProvider. $routeProvider service provides method when() and otherwise() to define the routes for your app. Routing has dependency on ngRoute module html <!-- Defining Route for your application --> <script type="text/javascript"> var myApp = angular.module('myApp', ['ngRoute']); myApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/products', { // Route templateUrl: 'views/products.html', controller: 'productController' }). when('/product/:productId', { // Route with parameter templateUrl: 'views/product.html', controller: 'productController' }). otherwise({ // Default route redirectTo: '/index' }); } ]); </script>

  2. What is AngularUI router and how it is different from ngRoute? - The UI-Router is a routing framework for AngularJS built by the AngularUI team. Unlike ngRoute, it changes your angular app views based on state of the app and not based on the route URL (ngRoute) - The ui-router helps you to create nested views, use multiple views on the same page, have multiple views that control a single view, and more - To use it you need to include reference of ui-router.js file into your angular app

  3. What is $injector and $inject? - $injector is a service which is used to invoke controller functions, service functions, filter functions, and any other function that might need dependencies as parameters. Angular creates only a single $injector object when an application is bootstrapped and uses that object for invoking

```html
<script>
var app = angular.module('app', []);
app.service('s1', function() {
    this.value = 22;
});
app.controller("MyCtrl", function($scope, $injector) {
    $scope.doSomething = function() {
        var s1 = $injector.get('s1')
        s1.value += 10
    }
    $scope.value = function() {
        var s1 = $injector.get('s1')
        return s1.value
    }
});
</script>
<div ng-app="app" ng-controller="MyCtrl">
    <button ng-click="doSomething()">increment</button> {{value()}}
</div>
```

- `$inject` is property which is used to inject the dependencies of a function as an array of strings

```html
<script type="text/javascript">
var MyController = function(renamed$scope, renamedGreeter) {
    // ...
}
MyController['$inject'] = ['$scope', 'greeter']; // Inject dependencies as an array of strings
</script>
```
  1. What is Dependency Injection in AngularJS? - Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. AngularJS comes with a built-in dependency injection mechanism. You can divide your AngularJS app into multiple different types of components which AngularJS can inject into each other - There are following 3 ways of injecting dependencies into your code:

    1. Implicitly from the function parameter names
      <script type="text/javascript">
      function MyController($scope, greeter) {
          // ...
      }
      </script>
    1. Using the $inject property annotation
      <script type="text/javascript">
      var MyController = function(renamed$scope, renamedGreeter) {
          // ...
      }
      MyController['$inject'] = ['$scope', 'greeter'];
      </script>
    1. Using the inline array annotation
      <script type="text/javascript">
      someModule.factory('greeter', ['$window', function(renamed$window) {
          // ...
      }]);
      </script>
  2. How to do Language Internationalization in AngularJS? - The angular-translate is an AngularJS module that brings i18n (internationalization) and l10n (localization) into your Angular app. It allows you to create a JSON file that represents translation data as per language. These languages specific JSON files can be lazy-loads from the server only when necessary. The angular-translate library (angular-translate.js) also provides built-in directives and filters that make the process of internationalizing simple ```html

<head>
    <title>AngularJS Internalization</title>
    <script src="lib/angular.js"></script>
    <script src="lib/angular-translate.js"></script>
    <script>
    var app = angular.module('myApp', ['pascalprecht.translate']);
    app.config(function($translateProvider) {
        $translateProvider.translations('en', {
                TITLE: 'Hello',
                PARA: 'This is a paragraph.',
                BUTTON_LANG_EN: 'english',
                BUTTON_LANG_DE: 'german'
            })
            .translations('de', {
                TITLE: 'Hallo',
                PARA: 'Dies ist ein Paragraph.',
                BUTTON_LANG_EN: 'englisch',
                BUTTON_LANG_DE: 'deutsch'
            });
        // Setting default language
        $translateProvider.preferredLanguage('en');
    });
    app.controller('TranslateController', function($translate, $scope) {
        $scope.changeLanguage = function(langKey) {
            $translate.use(langKey);
        };
    });
    </script>
</head>

<body ng-app="myApp">
    <div ng-controller="TranslateController">
        <h1>{{ 'TITLE' | translate }}</h1>
        <p>{{ 'PARA' | translate }}</p>
        <button ng-click="changeLanguage('en')" translate="BUTTON_LANG_EN"></button>
        <button ng-click="changeLanguage('de')" translate="BUTTON_LANG_DE"></button>
    </div>
</body>

</html>
```
  1. What is i18n and L10n? - i18n means Internationalization, where 18 stands for the number of letters in word Internationalization between the first i and last n. It is the process of developing products in such a way that they can be localized for languages and cultures easily - l10n means Localization, where 10 stand for the number of letters in word Localization between the first L and last n. It is the process of adapting applications and text to enable their usability in a particular culture

  2. What is $locale service? - $locale service provides localization rules for various Angular components. As of now the only public api is: id {string} - For example, a locale id is formatted as: languageId-countryId (e.g. en-us)

  3. What is a locale ID? - A locale is a specific geographical, political, or cultural region. The most commonly used locale ID consists of two parts: language code and country code. For example, en-US, en-AU, hi-IN are all valid locale IDs that have both language codes and country codes

  4. How to manage cookie in AngularJS? - AngularJS provides ngCookies module for reading and writing browser cookies. To use it include the angular-cookies.js file and set ngCookies as a dependency in your angular app. This module provides 2 services for cookie management: $cookies and $cookieStore

  5. What is difference between $cookies and $cookieStore service? - $cookies: This service provides read/write access to browser's cookies - If you want to use existing cookie solution, say read/write cookies from your existing server session system then use $cookie js var app = angular.module('cookiesExample', ['ngCookies']); app.controller('ExampleController', function($cookies) { // Retrieving a cookie var favoriteCookie = $cookies.myFavorite; // Setting a cookie $cookies.myFavorite = 'meal'; }); - $cookiesStore: $cookieStore is a thin wrapper around $cookies. It provides a key-value (string-object) storage that is backed by session cookies. The objects which are put or retrieved from this storage are automatically serialized or deserialized by angular to JSON and vice versa - If you are creating a new solution which will persist cookies based on key/value pairs, use $cookieStore js var app = angular.module('cookieStoreExample', ['ngCookies']); app.controller('ExampleController', function($cookieStore) { // Put cookie $cookieStore.put('myFavorite', 'meal'); // Get cookie var favoriteCookie = $cookieStore.get('myFavorite'); // Removing a cookie $cookieStore.remove('myFavorite'); });

  6. How to handle mobile browsers/devices events in AngularJS? - Mobile browsers/devices deal with events differently than desktop browsers. The AngularJS provide ngTouch library (angular-touch.js) to detect mobile browsers/devices events - For example, mobile browsers detect a tap event and then wait for second event about 300ms if any. So if we’re double-tapping the device then after this delay the browser fires a click event - In this way this delay can make our apps unresponsive. Hence, instead of dealing with the click event, we can detect touch event using ngTouch library. It handles touch detection for us through the ng-click directive. Hence it will take care of calling the correct click event for mobile html <button ng-click="save()">Save</button>

  7. How to detect swipe event in mobile browsers/devices in AngularJS? - The ngTouch library provides swipe directives to capture user swipes, either left or right across the screen. These events are useful when the user want to swipe to the next photo gallery photo or to a new portion of our app - The ngSwipeLeft directive detects when an HTML element is swiped from the right to the left and the ngSwipeRight directive detects when an HTML element is swiped from the left to the right

  8. How to do animation with the help of AngularJS? - AngularJS 1.2 comes with animation support via ngAnimate module. To enable animations within your angular app, you need to link the angular-animate.js file and include ngAnimate module as a dependency within your angular app

  9. What directives support animations? - The following directives support animations:

    1. ngRepeat: It supports enter, leave and move animations
    2. ngInclude: It supports enter and leave animations
    3. ngView: It supports enter and leave animations
    4. ngIf: It supports enter and leave animations
    5. ngSwitch: It supports enter and leave animations
    6. ngClass: It supports addClass and removeClass animations
    7. ngShow & ngHide: These support addClass and removeClass animations
  10. How to debug AngularJS app in browser? - AngularJS Batarang and ng-inspector are browser extensions for Chrome that adds an inspector pane into browser to debug and understand your AngularJS app. ng-inspector also works with safari browser - ng-inspector Extension:

  11. How to securely parse and manipulate your HTML data in AngularJS? - AngularJS provides ngSanitize module to securely parse and manipulate HTML data in your application. To use it include the angular-sanitize.js file and set ngSanitize as a dependency in your angular app js var app = angular.module('sanitizeExample', ['ngSanitize']); app.controller('ExampleController', function($scope, $sce) { var snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n snippet</p>'; $scope.trustedSnippet = $sce.trustAsHtml(snippet); //sce=Strict Contextual Escaping }); - The snippet may contain HTML, CSS, URLs and JavaScript code which you want to safely render in your app

  12. What is Angular 2.0? - Angular 2.0 is being written with AtScript, but that doesn't mean you have to write your application code with AtScript or know anything about AtScript to use Angular 2.0. You can easily write with TypeScript, ES6, ES5, CoffeeScript etc. whatever you like. It is still in development phase

  13. What is AtScript? - AtScript is Google’s new superset for JavaScript. It enhances JavaScript with new features to make it more robust. It is not only designed to run on top of ECMAScript 5 and ECMAScript 6, but on the top of Microsoft’s superset TypeScript language as well - The aim of AtScript is to make type annotation data available at runtime to enhance JavaScript with type, field and metadata annotations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment