61.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. 62.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: 63.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). 64.What is the difference between $parse and $eval?
$parse and $eval both operate on angular expressions i.e. {{ expression }}.
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>
javatechnologycenter.com </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) ); // javatechnologycenter.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. 65.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. 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}}' }; }); 66.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). 67.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. 68.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. 69.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.
<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: 'aarif mohammad', }; }); </script> Using Controller
<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> 70.How to share information between controllers in AngularJS? OR 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. 71.What is $emit, $broadcast and $on in AngularJS?
AngularJS provides $on, $emit, and $broadcast services for event-based communication between controllers.
<!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.$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> Parent ControllerEmit Message : www.javatechnologycenter.com Child Controller$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.
<!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> Parent ControllerChild ControllerBroadcast Message : {{message}} $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. 72.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. 73.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.
<input type="text"
ng-model="{ string }" [name="{ string }"] [ng-required="{ boolean }"] [ng-minlength="{ number }"] [ng-maxlength="{ number }"] [ng-pattern="{ string }"] [ng-change="{ string }"]> </input> 74.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.
//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 above created custom directive
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- Password --> <div> <label>Password</label> <input type="Password" name="password" ng-required="true" ng-model="user.password"> <p ng-show="userForm.password.$invalid">Your password is required.</p> </div> <!-- Confirm Password --> <div> <label>Confirm Password</label> <input type="Password" name="confirmPassword" ng-compare="password" ng- required="true" ng-model="user.confirmPassword" > <p ng-show="userForm.confirmPassword.$error.compare && !userForm.confirmPassword.$error.required">Confirm password doesn’t match.</p> </div> <!-- Other code has been removed for clarity--> </form> 75.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.
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. 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. 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. 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. Syntax
formName.$error
formName.inputFieldName.$error 76.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. 77.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. 78.What are different ways to create service in AngularJS?There are five ways to create a service as given below: 79.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.
//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. Example
//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. Example
//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.javatechnologycenter.com'); }); When to use: When you need to provide module-wise configuration for your service object before making it available. Example
<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("Aarif mohammad"); }); //defining controller app.controller('myController', function ($scope, myService, myFactory, configurable) { $scope.serviceName = myService.setName("Aarif mohammad"); myFactory.setName("Aarif mohammad"); $scope.factoryName = myFactory.name; $scope.providerName = configurable.name; }); </script> </body> </html> Output
From Service:Aarif mohammad
From Factory:Aarif mohammad From Provide:Aarif mohammad 80.What is difference between value and constant?
Value and Constant are simple objects which are used to share data globally with in a module.
//define module
var app = angular.module('app', []); //define value app.value("numberValue", 100); app.value("stringValue", "javatechnologycenter.com"); app.value("objectValue", { name: "javatechnologycenter.com", 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.
//define module
var app = angular.module('app', []); //define constant app.value("mynumberValue", 200); app.value("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); }); |