150 likes | 293 Views
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.
E N D
AngularJS ADMEC MULTIMEDIA INSTITUTE Akhilesh | AngularJS | October 22, 2015
Q1. What is AngularJS? Can you explain it technically? AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology. AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions. Features: AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA). AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way. Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0. Overall, AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
Q2. Explain AngularJS boot process please. 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: 1. 2.Create the application injector. 3.Compile the DOM starting from the ng-app root element. Load the module associated with the directive. This process is called auto-bootstrapping. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
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> Q3. Explain what is directive and mention what the different types of Directive in AngularJS? AngularJS directives are extended HTML attributes with the prefix ng-. ng-app − This directive starts an AngularJS Application. ng-init − This directive initializes application data. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
ng-model − This directive binds the value of HTML controls (input, select, textarea) to application data. ng-repeat − This directive repeats html elements for each item in a collection. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
Q4. Explain all the below given key features of AngularJS. a.Scope: 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. b.Controller: AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control. c.Model: Models are plain old JavaScript objects that represent data used by your app. Models are also used to represent your app's current state. d.View: 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. e.Services: Services are singletons, which are objects that are instantiated only once per app (by the $injector). They provide an interface to keep together methods that relate to a specific function. AngularJS provides many inbuilt services for example, $http, $route, $window, $location etc. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol. f.Data-binding: 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. g.Directives: Directives might just be the killer feature of AngularJS. Directives allow us to extend the grammar of the web through reusable HTML elements, attributes, and classes. AngularJS directives are extended HTML attributes with the prefix ng-. h.Filters: Filters are used to change modify the data and can be clubbed in expression or directives using pipe character. AngularJS filters can be used to transform data: 1.currency - Format a number to a currency format. 2. filter - Select a subset of items from an array. 3. lowercase - Format a string to lower case. 4. orderBy - Orders an array by an expression. 5. uppercase - Format a string to upper case. Q5. What is ng-app, ng-init and ng-model? Please explain in brief. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
ng-app: The ng-app directive defines the root element of an AngularJS application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded. Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or <html> tags. Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. You can specify an AngularJS module to be used as the root module for the application. This module will be loaded into the $injector when the application is bootstrapped. It should contain the application code needed or have dependencies on other modules that will contain the code. ng-init: ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. In following example, we'll initialize an array of countries. We're using JSON syntax to define array of countries. <div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en- GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]"> ... </div> This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope. ng-model: The ngModel directive binds an input, select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input, textarea or select require. Providing validation behavior (i.e. required, number, email, url). Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng- touched, ng-untouched, ng-empty, ng-not-empty) including animations. Registering the control with its parent form. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
Note: ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope. Q6. What are the key differences between AngularJS and jQuery? Framework If you compare jQuery and Angular, the former is a library and the latter is a framework. You can plug the library in your project and either use it fully, partially or not use it all. It’s like a plugin, a supplement to your JS project. With a framework – you have to play by its rules, either use it fully or don’t use it all. Angular.js is a MVC framework, it has model, view and controller which is one of the most popular software development architectures today. When developing with Angular, you have to start from the ground up with your architecture in mind. Although it’s possible to add Angular to your existing project, it’s just add more complexity in the long run. Don’t use Angular the jQuery way There are thousands of jQuery plugins out there, it’s very to just plug something in and forget about it. Angular has different structure, it’s recommended to use directives instead. Try to develop “the angular way” instead of just patching the code with old good plugins. It’s not even necessary to add jQuery to your project, Angular comes with jqLite (simplified version of jQuery for basic DOM manipulation). Single page application The architecture of the Angular app is different, most of them are single page applications (SPA). Instead of loading all the code at once like we do with jQuery and showing and hiding different parts of the DOM, we load templates on demand (using http requests). That way the application stays more modular and easier to maintain, debug or update. I like the approach where you create controller, module, HTML template and CSS file for every view in your app. Data Binding Data binding is one of the best features in Angular.js (one way or two way binding). This makes data completely independent from the presentation, unlike in jQuery where your model (data) is the DOM. For example, data comes from HTTP request (http module), it’s added to the scope ($scope.data) in controller and rendered in HTML template as ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
{{ data }} . This way you as a developer know where data is coming from and where you need to go to make any changes. In jQuery if you have something like $(‘#data’).render(); it may render a whole new page and you won’t event know what it is or where this content came from. Summary Angular doesn’t replace jQuery, it doesn’t compete with jQuery, they both can be used in the same application. jQuery for DOM manipulation, Angular – for structure. In fact there is nothing better to do DOM manipulation than jQuery. Q7. How will you initialize a select box with options on page load? <!doctype html> <html lang="en" data-ng-app="app"> <head> <meta charset="utf-8"> <title>Initialize Select Box</title> <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript"> angular.module('app', []) .controller('Main', function($scope) { $scope.model = {}; $scope.refmarkers = [{ ref: 'abc' }, { ref: 'def' }, { ref: 'ghi' }]; }); </script> </head> <body ng-controller="Main"> {{'Angular'}} <br> <br> <select ng-model="model.refmarker" ng-options="rm.ref for rm in refmarkers" ng- init="model.refmarker=refmarkers[0]"></select> <br> ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
<br> {{model.refmarker}} </body> </html> Q8. Explain what AngularJS routes does? AngularJS routes enable you to create different URLs for different content in your application. Having different URLs for different content enables the user to bookmark URLs to specific content, and send those URLs to friends etc. In AngularJS each such bookmarkable URL is called a route. AngularJS routes enables you to show different content depending on what route is chosen. A route is specified in the URL after the # sign. Thus, the following URL's all point to the same AngularJS application, but each point to different routes: http://myangularjsapp.com/index.html#books http://myangularjsapp.com/index.html#albums http://myangularjsapp.com/index.html#games http://myangularjsapp.com/index.html#apps When the browser loads these links, the same AngularJS application will be loaded (located at http://myangularjsapp.com/index.html), but AngularJS will look at the route (the part of the URL after the #) and decide what HTML template to show. At this point it may sound a little abstract, so let us look at a fully working AngularJS route example: <!DOCTYPE html> <html lang="en"> <head> <title>AngularJS Routes example</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script> </head> <body ng-app="sampleApp"> <a href="#/route1">Route 1</a><br/> <a href="#/route2">Route 2</a><br/> <div ng-view></div> <script> var module = angular.module("sampleApp", ['ngRoute']); module.config(['$routeProvider', ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
function($routeProvider) { $routeProvider. when('/route1', { templateUrl: 'angular-route-template-1.html, controller: 'RouteController' }). when('/route2', { templateUrl: 'angular-route-template-2.html, controller: 'RouteController' }). otherwise({ redirectTo: '/' }); }]); module.controller("RouteController", function($scope) { }) </script> </body> </html> Q9. Can you explain the concept of scope hierarchy? How many scopes can an application have? The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the root scope has one or more child scopes. Each view has its own $scope (which is a child of the root scope), so whatever variables one view controller sets on its $scope variable, those variables are invisible to other controllers. Look at this AngularJS code example: <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> </head> <body ng-app="myapp"> <div ng-controller="myController1"> {{data.theVar}} </div> <div ng-controller="myController2"> {{data.theVar}} </div> ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
<script> var module = angular.module("myapp", []); var myController1 = module.controller("myController1", function($scope) { $scope.data = { theVar: "Value One" }; }); var myController2 = module.controller("myController2", function($scope) { $scope.data = { theVar: "Value Two" }; }); </script> </body> </html> This example contains two views, each with their own controller function. Each controller sets the variable data.theVar to different values. When this example is executed, the $scope hierarchy will look like this: Root $scope $scope for myController 1 $scope for myController 2 As you can see, the $scope object used by the two controllers are not the same $scope object. That is also why the example above would write out two different values for the data bindings {{data.theVar}} inside the two views. The two controller functions for the views set different values for the data.theVar variable in each their own $scope object. 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 behaviour 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. Q10. Explain what are the factory methods in AngularJS? For creating the directive, factory method is used. It is invoked only once, when compiler matches the directive for the first time. By using $injector.invoke the factory method is invoked. Using factory method, we first define a factory and then assign method to it. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); Q11. What is deep linking in AngularJS? Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state. <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript" src="angular-route.min.js"></script> </head> <body> <div ng-app="DeepLinking"> [ <a href="#/welcome">Welcome</a> | <a href="#/settings">Settings</a> ] <hr/> <div ng-view></div> </div> <script type="text/javascript"> angular.module('DeepLinking', ["ngRoute"]) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/welcome', { template: '<html><body>Welcome!</body></html>' }) .when('/settings', { template: '<html><body>Settings</body></html>' }); }]); </script> </body> </html> ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
Q12. What is jQLite? 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. 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. <!DOCTYPE html> <html> <head> <script type="text/javascript" src="angular.min.js"></script> </head> <body ng-app="app"> <div ng-controller="mainCtrl"> <input type="text" id="txtName" value="Akhilesh Ojha" /> <button type="button" ng-click="clickme()">Click me</button> </div> <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> </body> </html> Q13. What are the disadvantages of AngularJS? Following are the disadvantages of AngularJS. Not Secure− Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure. Not degradable− If your application user disables JavaScript then user will just see the basic page and nothing more. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in
Q14. Explain $rootScope in AngularJS. Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables. Q15. Is AngularJS a templating system? At the highest level, Angular does look like 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. ADMEC MULTIMEDIA INSTITUTE C-7/114, 2nd Floor, Sector- 7, Rohini, Delhi- 85, Landmark: Near Rohini East Metro Station www.admecindia.co.in, +91 9811 818 122, +91 9911 782 350, info@admecindia.co.in