*
Previous AngularJS-QA-7 AngularJS-QA-9 Next

AngularJS Question Answers - 8

Question: What is the purpose of the directive 'ng-paste'?
Answer: ng-paste: Specifies a behavior on paste events.
Question: What is the purpose of the directive 'ng-pluralize'?
Answer: ng-pluralize: Specifies a message to display according to en-us localization rules.
Question: How to serialize to JSON string in AngularJS?
Answer: use angular.toJson() to serialize to JSON string.
//Object 
var myObj1 = [{name : 'Shiva', age : '28'},{name : 'Guru', age : '25'}]  
var myObj2 = {city : 'Benguluru', phone : '080-11111111'}  
  
document.write(angular.toJson(myObj1));  
document.write("</br>");  
document.write(angular.toJson(myObj2));  
document.write("</br>");  
    
Output:
[{"name":"Shiva","age":"28"},{"name":"Guru","age":"25"}]
{"city":"Benguluru","phone":"080-11111111"}
Question: What is the purpose of the directive 'ng-repeat'?
Answer: ng-repeat: Defines a template for each data in a collection.
Question: What is the purpose of the directive 'ng-selected'?
Answer: ng-selected: Specifies the selected attribute of an element.
Question: What is a $scope in AngularJS?
Answer: Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. Scopes are objects that refer to the model. They act as glue between controller and view. It can watch expressions and propagate events.
Question: What is the purpose of the directive 'ng-show'?
Answer: ng-show: Shows or hides HTML elements.
Question: What is the purpose of the directive 'ng-src'?
Answer: ng-src: Specifies the src attribute for the element.
Question: How do you share data between controllers?
Answer: Create an AngularJS service that will hold the data and inject it inside of the controllers.

Using a service is the cleanest, fastest and easiest way to test.
However, there are couple of other ways to implement data sharing between controllers, like:
– Using events
– Using $parent, nextSibling, controllerAs, etc. to directly access the controllers
– Using the $rootScope to add the data on (not a good practice)
The methods above are all correct, but are not the most efficient and easy to test.
Question: What are directives in AngularJS?
Answer: Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. When AngularJS finds the directive at the time of rendering then it attaches the requested behavior to the DOM element. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass.
Back to Index
Previous AngularJS-QA-7 AngularJS-QA-9 Next
*
*