Blog

AngularJS Interview Questions

Q. Databinding in angularjs
Angular remembers the value and compares it to previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.
The $apply() method, which is what you call when you are transitioning from non-angular world into angular world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.
To contrast dirty-checking (angular) vs change listeners (KO, backbone): While dirty-checking may seem simple, and even inefficient, (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KO dependency tracking is a clever feature for a problem which angular does not have.
Issues with change listeners:

  • Syntax is atrocious, since browsers do not support it natively, yes there are proxies but they are not semantically correct in all cases, and of course no proxies on old browsers. Bottom line is that dirty-checking allows you to do POJO, whereas KO and backbone force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine grained.
  • Change listeners fire immediately on setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JS avoids since each callback executes exclusively and to completion. Change events break this since setters can have far reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

Q. Cannot get to $rootScope
You can not ask for instance during configuration phase – you can ask only for providers.
Skip code block
var app = angular.module(‘modx’, []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});

Q. How to preventDefault on anchor tags?
UPDATE: I’ve since changed my mind on this solution. After more development and time spent working on this, I believe a better solution to this problem is to do the following:
Click Here
And then update your css to have an extra rule:
a{
cursor: pointer;
}
Its much more simple and provides the exact same functionality and is much more efficient. Hope that might be helpful to anyone else looking up this solution in the future.

Q. Difference between service, directive and module
Think of a module as being a place to wire up a number of other things, such as directives, services, constants etc. Modules can be injected into other modules giving you a high level of reuse.
When writing an angular app, you would have a top-level module which is your application code (sans templates)
services are mainly a way to communicate between controllers, but you can inject one service into another. services are often used as a way to get to your data stores and people will wrap the angular api’s such as ngResource. This technique is useful since it makes testing (particularly mocking) quite easy. You can have services for doing other things like authentication, logging etc.
directives are used for creating widgets or wrapping existing things like jquery plugins. Wrapping existing plugins can be a challenge and the reason you would do this is to establish a two-way data binding between the plugins and angular. If you don’t need two-way data binding then you don’t need to wrap them.
directives are also a place to do DOM manipulation, catching DOM-events etc. You should not be doing DOM-related stuff in controllers or services. creating directives can get pretty complex, IMHO, I recommend first looking to api for something that will do what you are looking to do OR ask angular googlegroup for advice.

Q. AngularJS – How to use $routeParams in generating the templateUrl?
I couldn’t find a way to inject and use the $routeParams service (which I would assume would be a better solution) I tried this thinking it might work:
angular.module(‘myApp’, []).
config(function ($routeProvider, $routeParams) {
$routeProvider.when(‘/:primaryNav/:secondaryNav’, {
templateUrl: ‘resources/angular/templates/nav/’+$routeParams.primaryNav+’/’+$routeParams.secondaryNav+’.html’
});
});
Which yielded this error: Unknown provider: $routeParams from myApp
If something like that isn’t possible you can change your templateUrl to point to a partial html file that just has ng-include and then set the url in your controller using $routeParams like this:

Skip code block
angular.module(‘myApp’, []).
config(function ($routeProvider) {
$routeProvider.when(‘/:primaryNav/:secondaryNav’, {
templateUrl: ‘resources/angular/templates/nav/urlRouter.html’,
controller: ‘RouteController’
});
});
function RouteController($scope, $routeParams) {
$scope.templateUrl= ‘resources/angular/templates/nav/’+$routeParams.primaryNav+’/’+$routeParams.secondaryNav+’.html’;
}
With this as your urlRouter.html

Q. In Angular Seed project, what is point of index-async.html?
I don’t see an app/index.ajax.html. I’m assuming you mean app/index-async.html.
The two files are interchangeable, and you can use either one to build your application. index-async.html loads scripts asynchronously, which might give you a faster bootstrap time. index.htmlloads scripts synchronously, which is often a bit slower, but the intention is that the code is easier to understand for someone learning to use the framework.
To read more about asynchronous bootstrapping, check out the docs here:http://docs.angularjs.org/guide/bootstrap
 
Learn how to use AngularJS, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free AngularJS Training Demo!

Q. angular.js link behaviour – disable deep linking for specific URLs
This is the code for turning off deep linking all together. It disables the click event handler from the rootElement.
angular.module(‘myApp’, [])
.run([‘$location’, ‘$rootElement’, function ($location, $rootElement) {
$rootElement.off(‘click’);
}]);

Q. this vs $scope in AngularJS controllers ?
“How does ‘this’ and $scope work in AngularJS controllers?”

  • this
    • When the controller constructor function is called,this is the controller.
    • When a function defined on a $scope object is called,this is the “scope in effect when the function was called”. This may (or may not!) be the $scope that the function is defined on. So, inside the function, this and $scope may not be the same.
  • $scope
    • Every controller has an associated $scope object.
    • A controller (constructor) function is responsible for setting model properties and functions/behavior on its associated $scope.
    • Only methods defined on this $scope object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click, filters, etc.

Q. How to get the url parameters using angular js
I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you’ll find an example for the route provider. To use params simply append them like this:
$routeProvider.when(‘/view1/:param1/:param2’, {
templateUrl: ‘partials/partial1.html’,
controller: ‘MyCtrl1’
});
Then in your controller inject $routeParams:
.controller(‘MyCtrl1’, [‘$scope’,’$routeParams’, function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param1 = $routeParams.param2;

}]);

Q. Angularjs: input[text] ngChange fires while the value is changing
This post shows an example of a directive that delays the model changes to an input until the blurevent fires.
Here is a fiddle that shows the ng-change working with the new ng-model-on-blur directive. Note this is a slight tweak to the original fiddle.
If you add the directive to your code you would change your binding to this:
Here is the directive:
Skip code block
// override the default input to update on blur
angular.module(‘app’, []).directive(‘ngModelOnblur’, function() {
return {
restrict: ‘A’,
require: ‘ngModel’,
priority: 1, // needed for angular 1.2.x
link: function(scope, elm, attr, ngModelCtrl) {
if (attr.type === ‘radio’ || attr.type === ‘checkbox’) return;
elm.unbind(‘input’).unbind(‘keydown’).unbind(‘change’);
elm.bind(‘blur’, function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
});
}
};
});
Note: this feature is supported directly in Angular 1.3 (currently in beta) via ngModelOptions.

Q. Accessing attributes from an AngularJS directive
And in the controller
Skip code block
var updateSelected = function(action, id) {
if (action === ‘add’ && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === ‘remove’ && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? ‘add’ : ‘remove’);
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? ‘add’ : ‘remove’);
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? ‘selected’ : ”;
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn’t resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

Although using ‘@’ is more appropriate than using ‘=’ for your particular scenario, sometimes I use ‘=’ so that I don’t have to remember to use attrs.$observe():
{{field.su_name}}
Directive:
Skip code block
myApp.directive(‘suLabel’, function() {
return {
restrict: ‘E’,
replace: true,
transclude: true,
scope: {
title: ‘=tooltip’
},
template: ‘’,
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass(‘tooltip-title’);
}
},
}
});
Fiddle.
With ‘=’ we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Q. Global variables in AngularJS
You’ve got basically 2 options for “global” variables:
use a$rootScope http://docs.angularjs.org/api/ng.$rootScope
use a servicehttp://docs.angularjs.org/guide/services
$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller’s scope. Services, being singletons are still ‘global’ but you’ve got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
var myApp = angular.module(‘myApp’,[]);
myApp.factory(‘UserService’, function() {
return {
name : ‘anonymous’
};
});
and then in a controller:
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/

Q. How does the $resource `get` function work synchronously in AngularJS?
$resource is not synchronous although this syntax might suggest that it is:
$scope.twitterResult = $scope.twitter.get();
What is going on here is that call to the AngularJS will, after call to twitter.get(), return immediately with the result being an empty array. Then, when the async call is finished and real data arrives from the server, the array will get updated with data. AngularJS will simply keep a reference to an array returned and will fill it in when data are available.
Here is the fragment of $resource implementation where the “magic” happens https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L372
This is described in the $resource documentation as well:
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.

Q. What are the additional js files of the Angular.js framework for?
AngularJS has base ng module (angular-1.0.1.js) which all basically use and some add-on modules. If you look at the api documentation you will see that the table of contents on the left side is divided into blocks: ng module, ngMock module, ngCookies module, etc.
angular-bootstrap-1.0.1.js seems as bootstrap-like implementations of dropdown and tabs. I think they are mainly used on angularjs.org. But can be used by anyone (thanks to the MIT license).
angular-cookies-1.0.1.js is ngCookies module which provide two services: $cookies and$cookieStore.
angular-loader-1.0.1.js as far as I understand should help to setup angular (ensure that all required modules loaded, etc) in external environments.
angular-resource-1.0.1.js is ngResource module which provide $resource service.
angular-sanitize-1.0.1.js is ngSanitize module which provide ngBindHtml directive, linky filter and$sanitize service.

Q. angularjs custom sort function in ng-repeat
Actually the orderBy filter can take as a parameter not only a string but also a function. From theorderBy documentation: http://docs.angularjs.org/api/ng.filter:orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I’m making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat=”card in cards | orderBy:myValueFunction”
Here is the working jsFiddle
The other thing worth noting is that orderBy is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy should be enough for most uses cases).

Q. How to assign alternate class to rows in Angular JS?
You should be using the angular directives ngClassEven and ngClassOdd for this.
Have a look at the documentation section for how to use them
HTTP://DOCS.ANGULARJS.ORG/API/NG.DIRECTIVE:NGCLASSEVEN
HTTP://DOCS.ANGULARJS.ORG/API/NG.DIRECTIVE:NGCLASSODD
Hope this helps.

Q. Controller Code Organization in Angular
We suggest putting at least some of those objects and their related calculations into services, then inject the services into your controller(s). See the Sticky Notes Part 1 blog entry for an example of a service that encapsulates some data and provides methods to access/manipulate that data.
See if you can break up your controller into multiple controllers, one for each view. A view can be as large as a page, or just some chunk/block on a page.
To quote from a google group post I saw recently: “I prefer to think of angular controllers as dumb apis/configs for my views and leave all the heavy lifting to services.” — reference

Q. angularjs: how to add caching to resource object?
Implementing your own cache in AngularJs is quite easy. Just use $cacheFactory:
Skip code block
app.factory(‘myService’, function($resource, $cacheFactory) {
var cache = $cacheFactory(‘myService’);
var User = $resource(‘/user/:userId’, {userId:’@id’});
return {
getResource: function(userId) {
var user = cache.get(userId);
if (!user) {
user = User.get({userId:userId});
cache.put(userId, user);
}
return user;
}
};
});

Q. How to Loop through items returned by a function with ng-repeat?
This was reported here and got this response:
Your getter is not idempotent and changes the model (by generating a new array each time it is called). This is forcing angular to keep on calling it in hope that the model will eventually stabilize, but it never does so angular gives up and throws an exception.
The values the getter return are equal but not identical and that’s the problem.
You can see this behavior go away if you move the array outside the Main controller:
var array = [{id:’angularjs’}];
function Main($scope) {
$scope.getEntities = function(){return array;};
};
because now it is returning the same object each time. You may need to re-architect your model to use a property on the scope instead of a function:
We worked around it by assigning the result of the controller’s method to a property, and doing ng:repeat against it.

Q. Is there a way to make AngularJS load partials in the beginning and not at when needed?
Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials – it adds a right click menu to create an HTML Bundle.
Add the code that this guy wrote to change the angular $templatecache service – its only a small piece of code and it works: Vojta Jina’s Gist
Its the $http.get that should be changed to use your bundle file:
allTplPromise = $http.get(‘templates/templateBundle.min.html’).then(
Your routes templateUrl should look like this:
$routeProvider.when(
“/about”, {
controller: “”,
templateUrl: “about.html”
}
);

Q. What’s the difference between ng-model and ng-bind
ng-bind has one-way data binding ($scope –> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html.
ng-model is intended to be put inside of form elements and has two-way data binding ($scope –> view and view –> $scope).

Check Out AngularJS Tutorials

Q. Better design for passing data to other ng-view’s and persisting it across controllers ?
across controllers by creating your own service as described nicely in this blog. You can also refer to this question.
In your case you can move your savePeopleResponse and getPeopleResponse into a service and then inject the service into any controllers you would like to access it.
Skip code block
angular.module(‘myApp’, [])
.factory(‘peopleService’, function () {
var peopleResponse = {};
return {
savePeopleResponse:function (data) {
peopleResponse = data;
console.log(data);
},
getPeopleResponse:function () {
return peopleResponse;
}
};
});
With your controller something like this:
function resultController ($scope, peopleService) {
$scope.getResultForPeople = peopleService.getPeopleResponse;
}
With this code example make sure you include ng-app=”myApp”

Q. Math functions in angular bindings
You have to inject Math into your scope, if you need to use it as $scope know nothing about Math.
Simplest way, you can do
$scope.Math = window.Math;
in your controller. Angular way to do this correctly would be create a Math service, I guess.

Q. Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document
I think that you are looking for the ngCloak directive:http://docs.angularjs.org/api/ng.directive:ngCloak
From the documentation:
The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
The directive can be applied to the element, but typically a fine-grained application is prefered in order to benefit from progressive rendering of the browser view.

Q. AngularJS dependency injection of value inside of module.config
The problem is that you are trying to inject a value object helpers in the config block of a AngularJS module and this is not allowed. You can only inject constants and providers in the config block.
The AngularJS documentation (section: “Module Loading & Dependencies”) gives the insight into this:
A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:
Configuration blocks – get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
Run blocks – get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Q. Format Date time in Angular JS
As the original string doesn’t include the “T” demarker, the default implementation in Angular doesn’t recognize it as a date. You can force it using new Date, but that is a bit of a pain on an array. Since you can pipe filters together, you might be able to use a filter to convert your input to a date and then apply the date: filter on the converted date. Create a new custom filter as follows:
app.
.filter(“asDate”, function () {
return function (input) {
return new Date(input);
}
});
Then in your markup, you can pipe the filters together:
{{item.myDateTimeString | asDate | date:’shortDate’}}

Q: Angular.js: Is .value() the proper way to set app wide constant and how to retrieve it in a controller
Answer: Module.value(key, value) is used to inject an editable value, Module.constant(key, value)is used to inject a constant value
The difference between the two isn’t so much that you “can’t edit a constant”, it’s more that you can’t intercept a constant with $provide and inject something else.
Skip code block
// define a value
app.value(‘myThing’, ‘weee’);
// define a constant
app.constant(‘myConst’, ‘blah’);
// use it in a service
app.factory(‘myService’, [‘myThing’, ‘myConst’, function(myThing, myConst){
return {
whatsMyThing: function() {
return myThing; //weee
},
getMyConst: function () {
return myConst; //blah
}
};
}]);
// use it in a controller
app.controller(‘someController’, [‘$scope’, ‘myThing’, ‘myConst’,
function($scope, myThing, myConst) {
$scope.foo = myThing; //weee
$scope.bar = myConst; //blah
});

Q. how to debug the $rootScope object of angularjs when in the browser
+1 for Batarang
Also, you can get the scope from any element in the DOM by executing the following from the console
angular.element(DOMNODE).scope()
Where DOMNODE, is of course, a reference to a DOM node.
For example, in Chrome in the elements tab you can select the node where the ng-app directive is, and get the root scope with
angular.element($0).scope()

Q. How to create angularjs filter which outputs HTML
I think ng-class is directive you need for this job and is safer then rendering to class attribute.
in your case just add object string with the id strings as the class and the value as the evaluated expression
‘icon-ok’:!phone.connectivity.infrared,
‘icon-remove’:phone.connectivity.infrared
}”>

on a side note, you should only use directives (built-in and custom) to manipulate html/dom and if you needed a more complex html render you should look at directive instead

Q. How to write a debounce service in AngularJS
Here is a working example of such a service: http://plnkr.co/edit/fJwRER?p=preview. It creates a$q deferred object that will be resolved when the debounced function is finally called.
Each time the debounce function is called the promise to the next call of the inner function is returned.
Skip code block
// Create an AngularJS service called debounce
app.factory(‘debounce’, [‘$timeout’,’$q’, function($timeout, $q) {
// The service is actually this function, which we call with the func
// that should be debounced and how long to wait in between calls
return function debounce(func, wait, immediate) {
var timeout;
// Create a deferred object that will be resolved when we need to
// actually call the func
var deferred = $q.defer();
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if(!immediate) {
deferred.resolve(func.apply(context, args));
deferred = $q.defer();
}
};
var callNow = immediate && !timeout;
if ( timeout ) {
$timeout.cancel(timeout);
}
timeout = $timeout(later, wait);
if (callNow) {
deferred.resolve(func.apply(context,args));
deferred = $q.defer();
}
return deferred.promise;
};
};
}]);
You get the return value from the debounced function by using the then method on the promise.
$scope.logReturn = function(msg) {
var returned = debounce($scope.addMsg, 2000, false);
console.log(‘Log: ‘, returned);
returned.then(function(value) {
console.log(‘Resolved:’, value);
});
};
If you call logReturn multiple times in quick succession you will see the promise logged over and over but only one resolved message.

Q. Can’t retrieve the injector from angular
Before answering the question we need to note that there is only one injector instance per application and not per module. In this sense it is not possible to retrieve an injector per module. Of course if we take the top-level module it represents the whole application so in this sense an application and top-level module seem equivalent. It might seem like a subtle difference but it is important to understand in order to fully and properly answer this question.
Next, from what I can understand you would like to retrieve the $injector and not create a new instance of it. The thing is that the angular.injector will create a new $injector instance for modules (an app) specified as arguments. Here the main AngularJS module (ng) must be specified explicitly. So, in this code example:
var injector = angular.injector([‘gaad’, ‘components’]);
you were trying to create a new injector from components defined in ‘gaad’ and ‘components’ modules and obviously $compileProvider is not defined in your custom modules. Adding the ngmodule to the list would “solve” the problem by creating a new injector – something that you probably don’t want to happen.
To actually retrieve an injector instance associated to a running application we can use 2 methods:

  • from within AngularJS JavaScript the simplest solution is just to inject$injector instance:http://docs.angularjs.org/api/angular.injector
  • from outside of AngularJS world – callelement([DOM element]).injector() where [DOM element] is a dome element where the ng-app was defined (or any child element of this element). More info here: http://docs.angularjs.org/api/angular.element

Here is the jsFiddle showing 2 methods of the injector retrieval: http://jsfiddle.net/Up2UC/
Please also note that using $injector directly is not very common scenario outside of unit testing. It might be useful thought for retrieving AngularJS services from outside of AngularJS world. More info here: Call Angular JS from legacy code.

Explore AngularJS Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Q. AngularJS – Access to child scope
Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.
While jm-‘s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope’s $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren’t documented so they might change without notice, but they’re there if you really need to traverse scopes.
// get $$childHead first and then iterate that scope’s $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
// cs is child scope
}
Fiddle

Q. $routeParams doesn’t work in resolve function
You need to use $route.current.params.key instead. The $routeParams is updated only after a route is changed. So your code should look along those lines:
NoteController.resolve = {
note: function($route, Note) {
return Note.get($route.current.params.key);
}
}

Q. how to access the angular $scope variable in browsers console
Pick an element in the HTML panel of the developer tools and type this in the console
angular.element($0).scope()
In webkit $0 is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console
Addons/Extensions
There are some very useful Chrome Extensions that you might want to checkout:

Playing with JS Fiddle
When working with jsfiddle you can open the fiddle in show mode by adding /show at the end of the url. When running like this you have access to the angular global. You can try it here
http://jsfiddle.net/jaimem/Yatbt/show
jQuery Lite
If you load jQuery before angular, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with
angular.element(‘[ng-controller=ctrl]’).scope()
Of a button
angular.element(‘button:eq(1)’).scope()
… and so on.
You might actually want to use a global function to make it easier
window.SC = function(selector){
return angular.element(selector).scope();
};
Now you could do this
SC(‘button:eq(10)’)
SC(‘button:eq(10)’).row   // -> value of scope.row
check here: http://jsfiddle.net/jaimem/DvRaR/1/show/

Q. confused about service vs factory
All angular services are singletons:
Docs (see Services as singletons): https://docs.angularjs.org/guide/services
Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.
Basically the difference between the service and factory is as follows:
Skip code block
app.service(‘myService’, function() {
// service is just a constructor function
// that will be called with ‘new’
this.sayHello = function(name) {
return “Hi ” + name + “!”;
};
});
app.factory(‘myFactory’, function() {
// factory returns an object
// you can run some code before
return {
sayHello : function(name) {
return “Hi ” + name + “!”;
}
}
});
Check out this presentation about $provide: http://slides.wesalvaro.com/20121113/#/
Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html


RELATED COURSES

Get Updates on Tech posts, Interview & Certification questions and training schedules