AngularJS Interview Questions

AngularJS Interview Questions

Q. What is the best way to conditionally apply a class?

If you don’t want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:

ng:class=”{true:’selected’, false:”}[$index==selectedIndex]”

Please note the old syntax with colon.

There is also a new better way of applying classes conditionally, like:

ng-class=”{selected: $index==selectedIndex}”

Angular now supports expressions that returns an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.

However these ways are not functionally equal. Here is an example:

ng-class=”{admin:’enabled’, moderator:’disabled’, ”:’hidden’}[user.role]”

We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time kept CSS classes out of Controller code.

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. Can I use another prefix instead of `ng` with angularjs?

Since v1.0.0rc1, these are all equivalent:

<div ng-show=”isVisible”>Using ng-show</div>
<div ng:show=”isVisible”>Using ng:show</div>
<div data-ng-show=”isVisible”>Using data-ng-show</div>
<div x-ng-show=”isVisible”>Using x-ng-show</div>
<div class=”ng-show:isVisible”>Using class=”ng-show:isVisible”</div>

Here’s working fiddle: http://jsfiddle.net/vojtajina/Fgf3Q/

However, the main reason behind this was allowing valid html. So, you ca use x-* prefix for your custom directives, but not for Angular ones.

Q. How would I render a dynamic definition list using angular?

A new feature which allows ng-repeat-start/ng-repeat-end was added in Angular 1.2.

With this feature, you can write your html like this:

<dt ng-repeat-start=”i in items”>{{i.key}}</dt>
<dd ng-repeat-end>{{i.value}}</dd>

See this plnkr for a full working example.

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. AngularJs: Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

Skip code block

angular.module(‘formComponents’, [])
.directive(‘formInput’, function() {
return {
restrict: ‘E’,
template: function(element, attrs) {
var type = attrs.type || ‘text’;
var required = attrs.hasOwnProperty(‘required’) ? “required=’required'” : “”;
var htmlText = ‘<div class=”sitb-control-group”>’ +
‘<label class=”sitb-control-label” for=”‘ + attrs.formId + ‘”>’ + attrs.label + ‘</label>’ +
‘<div class=”sitb-controls”>’ +
‘<input type=”‘ + type + ‘” class=”sitb-input-xlarge” id=”‘ + attrs.formId + ‘” name=”‘ + attrs.formId + ‘” ‘ + required + ‘>’ +
‘</div>’ +
return htmlText;
compile: function(element, attrs)
//do whatever else is necessary

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:

<a ng-click=”myFunction()”>Click Here</a>

And then update your css to have an extra rule:

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. AngularJS – How can I reference the property name within an ng-Repeat

Try this:

<li ng-repeat=”(key,val) in data”>{{key}}: {{val}}</li>

The problem with documentation is that it says “(key, value)” with that space … it took me some time to figure out that because of that it doesn’t work

Q. How do I switch views in AngularJS from a controller function?

In order to switch between different views, you could directly change the window.location (using the $location service!) in index.html file

<div ng-controller=”Cntrl”>
<div ng-click=”changeView(‘edit’)”>
<div ng-click=”changeView(‘preview’)”>


function Cntrl ($scope,$location) {
$scope.changeView = function(view){
$location.path(view); // path not hash

and configure the router to switch to different partials based on the location ( as shown herehttps://github.com/angular/angular-seed/blob/master/app/js/app.js ). This would have the benefit of history as well as using ng-view.

Alternatively, you use ng-include with different partials and then use a ng-switch as shown in here (https://github.com/ganarajpr/Angular-UI-Components/blob/master/index.html )

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

<div ng-include src=”templateUrl”></div>

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

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) {

Q. this vs $scope in AngularJS controllers ?

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

Short answer:

  • 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.

Long answer:

A controller function is a JavaScript constructor function. When the constructor function executes (e.g., when a view loads), this (i.e., the “function context”) is set to the controller object. So in the “tabs” controller constructor function, when the addPane function is created

this.addPane = function(pane) { … }

it is created on the controller object, not on $scope. Views cannot see the addPane function — they only have access to functions defined on $scope. In other words, in the HTML, this won’t work: <a ng-click=”addPane(newPane)”>won’t work</a>.

After the “tabs” controller constructor function executes, we have the following:


The dashed black line indicates prototypal inheritance — an isolate scope prototypically inherits from Scope. (It does not prototypically inherit from the scope in effect where the directive was encountered in the HTML.)

Now, the pane directive’s link function wants to communicate with the tabs directive (which really means it needs to affect the tabs isolate $scope in some way). Events could be used, but another mechanism is to have the pane directive require the tabs controller. (There appears to be no mechanism for the pane directive to require the tabs $scope.)

So, this begs the question: if we only have access to the tabs controller, how do we get access to the tabs isolate $scope (which is what we really want)?

Well, the red dotted line is the answer. The addPane() function’s “scope” (I’m referring to JavaScript’s function scope/closures here) gives the function access to the tabs isolate $scope. I.e., addPane() has access to the “tabs IsolateScope” in the diagram above because of a closure that was created when addPane() was defined. (If we instead defined addPane() on the tabs $scope object, the pane directive would not have access to this function, and hence it would have no way to communicate with the tabs $scope.)

To answer the other part of your question: how does $scope work in controllers?:

Within functions defined on $scope, this is set to “the $scope in effect where/when the function was called”. Suppose we have the following HTML:

<div ng-controller=”ParentCtrl”>
<a ng-click=”logThisAndScope()”>log “this” and $scope</a> – parent scope
<div ng-controller=”ChildCtrl”>
<a ng-click=”logThisAndScope()”>log “this” and $scope</a> – child scope

And the ParentCtrl has

$scope.logThisAndScope = function() {
console.log(this, $scope)

Clicking the first link will show that this and scope are the same, since “the scope in effect when the function was called” is the scope associated with the ParentCtrl.

Clicking the second link will reveal this and scope are not the same, since “the scope in effect when the function was called” is the scope associated with the ChildCtrl. So here, this is set to ChildCtrl’s $scope. Inside the method, $scope is still the ParentCtrl’s $scope.


We try to not use this inside of a function defined on $scope, as it becomes confusing which $scope is being affected, especially considering that ng-repeat, ng-include, ng-switch, and directives can all create their own child scopes.

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. Is it possible to make a Tree View with Angular?

When making something like this the best solution is an recursive directive. However, when you make such an directive you find out that AngularJS gets into an endless loop.

The solution for this is to let the directive remove the element during the compile event, and manually compile and add them in the link events.

I found out about this in this thread, and abstracted this functionality into a service.

Skip code block

module.factory(‘RecursionHelper’, [‘$compile’, function($compile){
return {
* Manually compiles the element, fixing the recursion loop.
* @param element
* @param [link] A post-link function, or an object with function(s) registered via pre and post properties.
* @returns An object containing the linking functions.
compile: function(element, link){
// Normalize the link parameter
link = { post: link };

// Break the recursion loop by removing the contents
var contents = element.contents().remove();
var compiledContents;
return {
pre: (link && link.pre) ? link.pre : null,
* Compiles and re-adds the contents
post: function(scope, element){
// Compile the contents
compiledContents = $compile(contents);
// Re-add the compiled contents to the element
compiledContents(scope, function(clone){

// Call the post-linking function, if any
if(link && link.post){
link.post.apply(null, arguments);

With this service you can easily make a tree directive (or other recursive directives). Here is an example of an tree directive:

Skip code block

module.directive(“tree”, function(RecursionHelper) {
return {
restrict: “E”,
scope: {family: ‘=’},
‘<p>{{ family.name }}</p>’+
‘<ul>’ +
‘<li ng-repeat=”child in family.children”>’ +
‘<tree family=”child”></tree>’ +
‘</li>’ +
compile: function(element) {
return RecursionHelper.compile(element);

See this Plunker for a demo. I like this solution best because:

  1. You don’t need an special directive which makes your html less clean.
  2. The recursion logic is abstracted away into the RecursionHelper service, so you keep your directives clean.

Update: Added support for a custom linking functions.

Q. How to alter the data returned by $resource in Angular.js?

I don’t think you need to modify the get or query defaults. Just use the success callback to do what you want. It should be more robust as well.

{}, //params
function (data) {   //success
$scope.entities = data.data;
function (data) {   //failure
//error handling goes here

Html will be cleaner, too:

<li ng-repeat=”entity in entities”>{{entity.title}}</<li>

By the way, I usually declare services for my resources and then inject them into my controllers as I need them.

myServices.factory(‘Entity’, [‘$resource’, function ($resource) {
return $resource(‘/api/entities’, {}, {

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:

<input type=”text” ng-model=”name” ng-model-onblur ng-change=”update()” />

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.bind(‘blur’, function() {
scope.$apply(function() {

Note: this feature is supported directly in Angular 1.3 (currently in beta) via ngModelOptions.

Q. How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I’ve been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that’s the way I’ve been playing with it).

The markup

Skip code block

<table class=”table”>
<input type=”checkbox”
<tr ng-repeat=”e in entities” ng-class=”getSelectedClass(e)”>
<input type=”checkbox” name=”selected”
ng-click=”updateSelection($event, e.id)”>

And in the controller

Skip code block

var updateSelected = function(action, id) {
if (action === ‘add’ && $scope.selected.indexOf(id) === -1) {
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

Q. Accessing attributes from an AngularJS directive

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():

<su-label tooltip=”field.su_documentation”>{{field.su_name}}</su-label>


Skip code block

myApp.directive(‘suLabel’, function() {
return {
restrict: ‘E’,
replace: true,
transclude: true,
scope: {
title: ‘=tooltip’
template: ‘<label><a href=”#” rel=”tooltip” title=”{{title}}” data-placement=”right” ng-transclude></a></label>’,
link: function(scope, element, attrs) {
if (scope.title) {


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. Not polluting global with angularjs

One of the ways around it is to define it within Angular itself such as the way you described. In other words:

angular.module(‘YourApp’).controller(‘ControllerName’, function($scope) {})

I have confirmed the above method doesn’t pollute the global namespace.

Edit: You also don’t need to use <div ng-controller=”myApp.UserController”> as you could define myApp in the attribute ng-app: <body ng-app=”myApp”> That way you could call the ng-controller without prefixing myApp every time.

Q. How to set value property in angularjs ng-options?


ngOptions(optional) {comprehension_expression=} in one of the following forms:

for array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
for object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object

In this case, it should be

array = [{ “value”: 1, “text”: “1st” }, { “value”: 2, “text”: “2nd” }];

<select ng-options=”obj.value as obj.text for obj in array”></select>


With the updates on Angular, it is now possible to set the actual value for the value attribute ofselect element with track by expression.

<select ng-options=”obj.text for obj in array track by obj.value”>

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



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. Sorting dropdown alphabetically in AngularJS

You should be able to use filter. ‘orderBy’ can accept 3rd option for ‘reverse’ flag.

<select ng-option=”item.name for item in items | orderBy:’name’:true></select>

Here item is sorted by ‘name’ property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

@see http://docs.angularjs.org/api/ng.filter:orderBy

Q. Angularjs clicking a button within a form causes page refresh

If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type=’button’ when you don’t want them to submit.

The thing to note in particular is where it says

A button element with no type attribute specified represents the same thing as a button element with its type attribute set to “submit”

You can try to prevent default handler:


<button ng-click=”saveUser($event)”>


$scope.saveUser = function (event) {
// your code

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. angular js unknown provider

I just had a similar problem. The error said the same the in the question, tried to solve it with the answer of pkozlowski.opensource and Ben G, which both are correct and good answers.

My problem was indeed different with the same error:

in my HTML-Code I had the initialisation like this…

<html ng-app>

A bit further down I tried to do something like this:

<div id=”cartView” ng-app=”myApp” ng-controller=”CartCtrl”>

I got rid of the first one… then it worked… obviously you can’t initialise ng-app twice or more times. fair enough.

I totaly forgot about the first “ng-app” and got totaly frustrated. Maybe this is gonna help someone oneday…

Q. Angular JS ng-repeat handle empty list case

 You can use ngShow.

<li ng-show=”!events.length”>No events</li>

See example.

Or you can use ngHide

<li ng-hide=”events.length”>No events</li>

See example.

For object you can test Object.keys.

Q. Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id=”about.html” type=”text/ng-template”>
This is the About page
Its cool!

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:

“/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) e.g. <input ng-model=”val”/>.

Q. AngularJS Paging with $location.path but no ngView reload

instead of updating the path, just update query param with a page number.

set your route to ignore query param changes:

$routeProvider.when(‘/foo’, {…, reloadOnSearch: false})

and in your app update $location with:

$location.search(‘page’, pageNumber);

Q. AngularJS ng-include does not include view unless passed in $scope

ng-include accepts an expression. If you want to specify the explicit url directly in there, you have to give a string.

<div ng-include src=”‘page.html'”></div>

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;
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. How to add custom validation to an Angular js form?

Angular-UI’s project includes a ui-validate directive, which will probably help you with this. It let’s you specify a function to call to do the validation.

Have a look at the demo page: http://angular-ui.github.com/, search down to the Validate heading.

From the demo page:

<input ng-model=”email” ui-validate='{blacklist : notBlackListed}’>
<span ng-show=’form.email.$error.blacklist’>This e-mail is black-listed!</span>

then in your controller:

function ValidateCtrl($scope) {
$scope.blackList = [‘bad@domain.com’,’verybad@domain.com’];
$scope.notBlackListed = function(value) {
return $scope.blackList.indexOf(value) === -1;

Q. How to highlight a current menu item?

 Here’s a simple approach that works well with Angular.

<li ng-class=”{ active: isActive(‘/View1’) }”><a href=”#/View1″>View 1</a></li>
<li ng-class=”{ active: isActive(‘/View2’) }”><a href=”#/View2″>View 2</a></li>
<li ng-class=”{ active: isActive(‘/View3’) }”><a href=”#/View3″>View 3</a></li>

Within your AngularJS controller:

$scope.isActive = function (viewLocation) {
var active = (viewLocation === $location.path());
return active;

Q. How is modularity mitigated in AngularJS?

It can be easily done without any modifications to Angular sources (version 1.0.2).

Repository: https://github.com/matys84pl/angularjs-requirejs-lazy-controllers .

There is also an implementation that uses yepnope (https://github.com/cmelion/angular-yepnope) made by Charles Fulnecky.

Q. How can you pass a bound variable to an ng-click function?

You don’t need to use curly brackets ({{}}) in the ng-click, try this:

<button class=”btn btn-danger” ng-click=”delete(submission.id)”>delete</button>

Q. AngularJS and its use of Dollar Variables

There are a few times Angular ignores variables prefixed with the dollar sign:

  1. InSchumli’s comment below, where json filters will not output them
  2. When using the{{ }} directive, angular will not show nested $  For example this only displays the visible property.

<div ng-init=”n = { visible: ‘foo’, $ignore: ‘bar’ };”>{{ n }}</div>

  1. Additionally when adding an explicit watcher on a scope object, changes to properties with a leading dollar sign of this object will not trigger the watcher. Seethis updated fiddle.
  2. equals()ignores keys prefixed with $.

Q. Why does angularjs include an empty option in select

The empty option is generated when a value referenced by ng-model doesn’t exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don’t want to decide model value on its own.

If you want to get rid of the empty option just select an initial value in your controller, something like:

$scope.form.type = $scope.typeOptions[0].value;

Here is the jsFiddle: http://jsfiddle.net/MTfRD/3/

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

Q. Angular js support for localization ?

What you’re looking for is $locale.

There is actually an example about half way down the angularjs homepage as well.

A snippet from their example:

Skip code block

function BeerCounter($scope, $locale) {
$scope.beers = [0, 1, 2, 3, 4, 5, 6];
if ($locale.id == ‘en-us’) {
$scope.beerForms = {
0: ‘no beers’,
one: ‘{} beer’,
other: ‘{} beers’
} else {
$scope.beerForms = {
0: ‘iadne pivo’,
one: ‘{} pivo’,
few: ‘{} piv’,
other: ‘{} pv’

If you had a lot of localization to do, I think I would just create a service to inject in my controllers… something like this psuedo-code:

Skip code block

app.service(‘myLocalization’, [‘$locale’, function($locale) {
var res = {
‘help’ : {
‘en-us’: ‘help’,
‘es-mx’: ‘ayudame’
‘beer’ : {
‘en-us’: ‘beer’,
‘es-mx’: ‘cerveza’

return {
getString: function(key) {
return res[key][$locale.id];

Q. Angular JS update input field after change

I’m guessing that when you enter a value into the totals field that value expression somehow gets overwritten.

However, you can take an alternative approach: Create a field for the total value and when eitherone or two changes update that field.

<li>Total <input type=”text” ng-model=”total”>{{total}}</li>

And change the javascript:

function TodoCtrl($scope) {
$scope.$watch(‘one * two’, function (value) {
$scope.total = value;

Example fiddle here.

Q. How to format a telephone number in AngularJS ?

Also, if you need to format telephone number on output only, you can use custom filter like this one:

Skip code block

angular.module(‘ng’).filter(‘tel’, function () {
return function (tel) {
if (!tel) { return ”; }

var value = tel.toString().trim().replace(/^\+/, ”);

if (value.match(/[^0-9]/)) {
return tel;

var country, city, number;

switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);

case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);

case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);

return tel;

if (country == 1) {
country = “”;

number = number.slice(0, 3) + ‘-‘ + number.slice(3);

return (country + ” (” + city + “) ” + number).trim();

Then you can do the folloing in template:

{{ phoneNumber | tel }}
<span ng-bind=”phoneNumber | tel”></span>

Q. AngularJS – Using Partials Dynamically Within Other Partials

There are a couple approaches available to you.

Your best bet is to add your own directive. Expanding on your example:

module.directive(‘myModule’, function() {
return {
restrict: ‘A’,
scope : {
title : ‘@’
templateUrl : ‘/partial/module.html’,
transclude : true

We’ll use transclusion to make the contents more flexible. Now the partial:

<div class=”module”>
<h2 class=”module-title”>{{title}}</h2>

<div class=”module-content” ng-transclude></div>

With this directive installed, you can use the following HTML:

<div my-module title=”{{module.title}}”>

Another option is to use the ng-include directive. This is a simple transclusion of a partial, the difference being that the transcluded partial lives in the same scope as the context it was included in.

<div ng-include=”module.partialUrl”></div>

In the above case, Angular will transclude the partial at the URL at $scope.module.partialUrl. (Edit: this means you can dynamically substitute out UIs by replacing the scope variable used by ngInclude. Awesome, right?)

If you’re just reusing the same partial to avoid repetitive code, then simply surround the URL in single quotes:

<div ng-include=”‘/partial/foo.html'”></div>

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. Complex nesting of partials and templates

Well, since you can currently only have one ngView directive… we can use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that we use ng-switch or even just ng-show to choose which controls I’m displaying based on what’s coming in from $routeParams.

EDIT Here’s some example pseudo-code to give you an idea of what I’m talking about. With a nested sub navigation.

Here’s the main app page

<!– primary nav –>
<a href=”#/page/1″>Page 1</a>
<a href=”#/page/2″>Page 2</a>
<a href=”#/page/3″>Page 3</a>

<!– display the view –>
<div ng-view>

Directive for the sub navigation

Skip code block

app.directive(‘mySubNav’, function(){
return {
restrict: ‘E’,
scope: {
current: ‘=current’
templateUrl: ‘mySubNav.html’,
controller: function($scope) {

template for the sub navigation

<a href=”#/page/1/sub/1″>Sub Item 1</a>
<a href=”#/page/1/sub/2″>Sub Item 2</a>
<a href=”#/page/1/sub/3″>Sub Item 3</a>

template for a main page (from primary nav)

Skip code block

<my-sub-nav current=”sub”></my-sub-nav>

<ng-switch on=”sub”>
<div ng-switch-when=”1″>
<div ng-switch-when=”2″>
<div ng-switch-when=”3″>

Controller for a main page. (from the primary nav)

app.controller(‘page1Ctrl’, function($scope, $routeParams) {
$scope.sub = $routeParams.sub;

Directive for a Sub Area

app.directive(‘mySubArea1’, function(){
return {
restrict: ‘E’,
templateUrl: ‘mySubArea1.html’,
controller: function($scope) {
//controller for your sub area.

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 <body> 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:

.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. What is the angularjs way to databind many inputs?

You’ll have better luck if your list is an array of objects (as opposed to an array of primitives). This works fine even though a new scope is created with ng-repeat:

<div ng-repeat=”item in list”>
<label>Input {{$index+1}}:</label>
<input ng-model=”item.value” type=”text”/>

with a controller of:

function TestController($scope) {
$scope.list = [ { value: ‘value 1’ }, { value: ‘value 2’ }, { value: ‘value 3’ } ];

See this fiddle as an example.

On the other hand if you are trying to bind to an array of strings the new scope will cause a problem as the values you are modifying will not be tied to the original array string primitives (as in this fiddleexample).

Q. in angularjs how to access the element that triggered the event?

The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:

app.directive(‘myChange’, function() {
return function(scope, element) {
element.bind(‘change’, function() {
alert(‘change on ‘ + element);

The above directive can be used as follows:

<input id=”searchText” ng-model=”searchText” type=”text” my-change>

Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element.

Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.

Although you can get the element via the $event object:

<button ng-click=”clickit($event)”>Hello</button>

$scope.clickit = function(e) {
var elem = angular.element(e.srcElement);

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. Need some examples of binding attributes in custom AngularJS tags

Youre pretty close..

Skip code block

app.directive(‘mytag’,function() {
return {
restrict: ‘E’,
template: ‘<div>’ +
‘<input ng-model=”controltype”/>’ +
‘<button ng-click=”controlfunc()”>Parent Func</button>’ +
‘<p>{{controlval}}</p>’ +
scope: {
/* make typeattribute=”whatever” bind two-ways (=)
$scope.whatever from the parent to $scope.controltype
on this directive’s scope */
controltype: ‘=typeattribute’,
/* reference a function from the parent through
funcattribute=”somefunc()” and stick it our
directive’s scope in $scope.controlfunc */
controlfunc: ‘&funcattribute’,
/* pass a string value into the directive */
controlval: ‘@valattribute’
controller: function($scope) {

<div ng-controller=”ParentCtrl”>
<!– your directive –>
<mytag typeattribute=”parenttype” funcattribute=”parentFn()” valattribute=”Wee, I’m a value”></mytag>
<!– write out your scope value –>

app.controller(‘ParentCtrl’, function($scope){
$scope.parenttype = ‘FOO’;
$scope.parentFn = function() {
$scope.parenttype += ‘!!!!’;

The magic is mostly in the scope: declaration in your directive definition. having any scope: {}in there will “isolate” the scope from the parent, meaning it gets it’s own scope… without that, it would use the parent’s scope. The rest of the magic is in the scope’s properties: scope: { ‘internalScopeProperty’ : ‘=externalAttributeName’ }… where the = represents a two way binding scenario. If you change that = to a @ you’ll see it just allows you to pass a string as an attribute to the directive. The & is for executing functions from the parent scope’s context.

I hope that helps.

Q. Working with select using Angular’s ng-options

I’m learning angularjs and was struggling with selection as well. I know this question is already answered but wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. Models list is disabled until some make is selected. If selection in makes listbox is later reset (set to ‘Select Make’) then models listbox becomes disabled again AND its selection is reset as well (to ‘Select Model’). Makes are retrieved as resource while models are just hard-coded.

Makes JSON:

{“code”: “0”, “name”: “Select Make”},
{“code”: “1”, “name”: “Acura”},
{“code”: “2”, “name”: “Audi”}


angular.module(‘makeServices’, [‘ngResource’]).
factory(‘Make’, function($resource){
return $resource(‘makes.json’, {}, {
query: {method:’GET’, isArray:true}

HTML file:

Skip code block

<div ng:controller=”MakeModelCtrl”>
<select id=”makeListBox”
ng-options=”make.code as make.name for make in makes”

<select id=”modelListBox”
ng-options=”model.code as model.name for model in models”>


Skip code block

function MakeModelCtrl($scope)
$scope.makeNotSelected = true;
$scope.make = {selected: “0”};
$scope.makes = Make.query({}, function (makes) {
$scope.make = {selected: makes[0].code};

$scope.makeChanged = function(selectedMakeCode) {
$scope.makeNotSelected = !selectedMakeCode;
if ($scope.makeNotSelected)
$scope.model = {selected: “0”};

$scope.models = [
{code:”0″, name:”Select Model”},
{code:”1″, name:”Model1″},
{code:”2″, name:”Model2″}
$scope.model = {selected: “0”};

Hope it makes sense and will help to somebody.

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


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


Q. What exactly do you do with the transclude function and the clone linking function?

EDIT: Completely and totally changing my answer and marking this as “Community Wiki” (meaning no points for me) as I was outright wrong when I answered this

As @Jonah pointed out below, here is a really good article on the compile option of directives and using the transclusion function

The basic idea is the compile function should return a linking function. You can use the transclusion function provided inside the linking function to take a clone of the transcluded DOM element, compile it, and insert it wherever it needs to be inserted.

Here is a better example I’ve pulled out of my butt on Plunker

The idea of the compile function is it gives you a chance to programmatically alter the DOM elements based on attributes passed BEFORE the linking function is created and called.

Skip code block

// a silly directive to repeat the items of a dictionary object.
app.directive(‘keyValueRepeat’, function ($compile){
return {
transclude: true,
scope: {
data: ‘=’,
showDebug: ‘@’
compile: function(elem, attrs, transclude) {

if(attrs.showDebug) {
elem.append(‘<div class=”sitb-debug”>DEBUG ENABLED {{showDebug}}</div>’);

return function(scope, lElem, lAttrs) {
var items = [];
scope.$watch(‘data’, function(data) {

// remove old values from the tracking array
// (see below)
for(var i = items.length; i– > 0;) {

//add new ones
for(var key in data) {

var val = data[key],
childScope = scope.$new(),
childElement = angular.element(‘<div></div>’);

// for each item in our repeater, we’re going to create it’s
// own scope and set the key and value properties on it.
childScope.key = key;
childScope.value = val;

// do the transclusion.
transclude(childScope, function(clone, innerScope) {
//clone is a copy of the transcluded DOM element content.

// Because we’re still inside the compile funciton of the directive,
// we can alter the contents of each output item
// based on an attribute passed.
if(attrs.showDebug) {
clone.prepend(‘<span class=”sitb-debug”>{{key}}: {{value}}</span>’);

//append the transcluded element.

// add the objects made to a tracking array.
// so we can remove them later when we need to update.
element: childElement,
scope: childScope


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

<i ng-class=”{

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. Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

Skip code block

<div ng-controller=”MyCtrl”>
<h2>Parent Scope</h2>
<input ng-model=”foo”> <i>// Update to see how parent scope interacts with component scope</i>
<!– attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. –>
<my-component attribute-foo=”{{foo}}” binding-foo=”foo”
isolated-expression-foo=”updateFoo(newFoo)” >
<strong>get:</strong> {{isolatedAttributeFoo}}
<strong>set:</strong> <input ng-model=”isolatedAttributeFoo”>
<i>// This does not update the parent scope.</i>
<strong>get:</strong> {{isolatedBindingFoo}}
<strong>set:</strong> <input ng-model=”isolatedBindingFoo”>
<i>// This does update the parent scope.</i>
<input ng-model=”isolatedFoo”>
<button class=”btn” ng-click=”isolatedExpressionFoo({newFoo:isolatedFoo})”>Submit</button>
<i>// And this calls a function on the parent scope.</i>

Skip code block

var myModule = angular.module(‘myModule’, [])
.directive(‘myComponent’, function () {
return {
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
.controller(‘MyCtrl’, [‘$scope’, function ($scope) {
$scope.foo = ‘Hello!’;
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;

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 = $timeout(later, wait);
if (callNow) {
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.

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


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. Error: “Selectors not implemented”

It’s because jquery needs to be referenced before angular. JSFiddle registered Angular 1.0.2 FIRST and then the jquery verson you added as a resource.

<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script src=”//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js”></script>

This way Angular knows it can use JQuery and not JQLite. Once you do this, the selector will work in angular.element()

Here’s your fiddle, updated to reference the scripts in the right order (and altered slightly, see the comments)

If you don’t have JQuery, you can select the DOM Element manually.

var div = document.querySelector(‘div’);
$scope.elem = angular.element(div);

Q. Reusable components in AngularJS

I was finally able to solve this. It is pretty easy after your read the documentation and play around

Here is the directive:

Skip code block

angular.module(‘components’, []).directive(‘category’, function () {
return {
restrict: ‘E’,
scope: {},
templateUrl: ‘/Scripts/app/partials/CategoryComponent.html’,
controller: function ($scope, $http, $attrs) {
url: “api/FeaturedProducts/” + $attrs.catName,
method: “get”
}).success(function (data, status, headers, config) {
$scope.Cat = data;
}).error(function (data, status, headers, config) {
$scope.data = data;
$scope.status = status;


This this the main page with the same component called multiple times but with different parameter

Skip code block

<ul class=”unstyled”>
<category cat-name=”Ultrabooks”></category>
<category cat-name=”Tablets”></category>
<category cat-name=”Laptops”></category>
<category cat-name=”Digital SLR Cameras”></category>


Skip code block

<a href=”#/Categories/{{Cat.CategoryName}}”>
<div ng-switch on=”status”>
<div ng-switch-when=”500″ class=”alert alert-error”>
<div ng-switch-default>
<ul class=”unstyled columns”>
<li class=”pin” ng-repeat=”p in Cat.Products”>
<a href=”#/reviews/{{p.UPC}}”>
<img src=”{{p.ImageUrl}}”>

Q. How to ‘unwatch’ an expression

To have a repeater with a large array that you don’t watch to watch every item.

You’ll need to create a custom directive that takes one argument, and expression to your array, then in the linking function you’d just watch that array, and you’d have the linking function programmatically refresh the HTML (rather than using an ng-repeat)

something like (psuedo-code):

Skip code block

app.directive(‘leanRepeat’, function() {
return {
restrict: ‘E’,
scope: {
‘data’ : ‘=’
link: function(scope, elem, attr) {
scope.$watch(‘data’, function(value) {
elem.empty(); //assuming jquery here.
angular.forEach(scope.data, function(d) {
//write it however you’re going to write it out here.
elem.append(‘<div>’ + d + ‘</div>’);

… which seems like a pain in the butt.

Alternate hackish method

You might be able to loop through $scope.$$watchers and examine$scope.$$watchers[0].exp.exp to see if it matches the expression you’d like to remove, then remove it with a simple splice() call. The PITA here, is that things like Blah {{whatever}} Blahbetween tags will be the expression, and will even include carriage returns.

On the upside, you might be able to just loop through the $scope of your ng-repeat and just remove everything, then explicitly add the watch you want… I dunno.

Either way, it seems like a hack.

To remove a watcher made by $scope.$watch

You can unregister a $watch with the function returned by the $watch call:

For example, to have a $watch only fire once:

var unregister = $scope.$watch(‘whatever’, function(){

You can, of course call the unregister function any time you want… that was just an example.

Conclusion: There isn’t really a great way to do exactly what you’re asking

But one thing to consider: Is it even worth worrying about? Furthermore is it truly a good idea to have thousands of records loaded into dozens of DOMElements each? Food for thought.

I hope that helps.

Q. Difficulty with ng-model, ng-repeat, and inputs

This seems to be a binding issue.

The advice is don’t bind to primitives.

Your ngRepeat is iterating over strings inside a collection, when it should be iterating over objects. To fix your problem

<body ng-init=”models = [{name:’Sam’},{name:’Harry’},{name:’Sally’}]”>
<h1>Fun with Fields and ngModel</h1>
<p>names: {{models}}</p>
<h3>Binding to each element directly:</h3>
<div ng-repeat=”model in models”>
Value: {{model.name}}
<input ng-model=”model.name”>

jsfiddle: http://jsfiddle.net/jaimem/rnw3u/5/

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


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


There are some very useful Chrome Extensions that you might want to checkout:

  • Batarang. This has been around for a while.
  • ng-inspector. This is the newest one, and as the name suggests, it allows you to inspect your application’s scopes.

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


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


Of a button


… 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)’).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

Q. Angular js init ng-model from default values

This is an obviously lacking, but easily added fix for AngularJS. Just write a quick directive to set the model value from the input field.

<input name=”card[description]” value=”Visa-4242″ ng-model=”card.description” ng-initial>

Here’s my version:

Skip code block

var app = angular.module(‘forms’, []);

app.directive(‘ngInitial’, function() {
return {
restrict: ‘A’,
controller: [
‘$scope’, ‘$element’, ‘$attrs’, ‘$parse’, function($scope, $element, $attrs, $parse) {
var getter, setter, val;
val = $attrs.ngInitial || $attrs.value;
getter = $parse($attrs.ngModel);
setter = getter.assign;
setter($scope, val);

Q. Different ng-include’s on the same page: how to send different variables to each?

The expression passed to onload evaluates every time a new partial is loaded. In this case you are changing the values of var twice so by the time both partials are loaded the current value will be B

You want to pass different data to each partial/template (with the underlying html file being the same). To achieve this, as Tiago mentions, you could do it with different controllers. For example, consider the following

<body ng-controller=’MainCtrl’>
<div ng-include src='”toBeIncluded.html”‘ ng-controller=’ctrlA’ onload=”hi()”></div>
<div ng-include src='”toBeIncluded.html”‘ ng-controller=’ctrlB’ onload=”hi()”></div>

Here, we have two partials, each with its own scope managed from their own controller (ctrlA andctrlB), both children scopes of MainCtrl. The function hi() belongs to the scope of MainCtrl and will be run twice.

If we have the following controllers

Skip code block

app.controller(‘MainCtrl’, function($scope) {
$scope.msg = “Hello from main controller”;
$scope.hi= function(){console.log(‘hi’);};

app.controller(‘ctrlA’, function($scope) {
$scope.v = “Hello from controller A”;

app.controller(‘ctrlB’, function($scope) {
$scope.v = “Hello from controller B”;

And the contents of toBeIncluded.html are

<p>value of msg = {{msg}}</p>
<p>value of v = {{v}} </p>

The resulting html would be something along the following lines

<p>value of msg = Hello from main controller</p>
<p>value of v = Hello from main controller A </p>


<p>value of msg = Hello from main controller</p>
<p>value of v = Hello from controller B </p>

Example here: http://plnkr.co/edit/xeloFM?p=preview

Q. How to config routeProvider and locationProvider in angularJS?

The only issue I see are relative links and templates not being properly loaded because of this.

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href=”/my-base”>) or you must use absolute urls (starting with/) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.

In you case you can add a forward slash / in href attributes ($location.path does thisautomatically) and also to templateUrl when configuring routes. This avoids routes likeexample.com/tags/another and makes sure templates load properly.

Here’s an example that works:

<a href=”/”>Home</a> |
<a href=”/another”>another</a> |
<a href=”/tags/1″>tags/1</a>
<div ng-view></div>


Skip code block

app.config(function($locationProvider, $routeProvider) {
.when(‘/’, {
templateUrl: ‘/partials/template1.html’,
controller: ‘ctrl1’
.when(‘/tags/:tagId’, {
templateUrl: ‘/partials/template2.html’,
controller:  ‘ctrl2’
.when(‘/another’, {
templateUrl: ‘/partials/template1.html’,
controller:  ‘ctrl1’
.otherwise({ redirectTo: ‘/’ });

If using Chrome you will need to run this from a server.

Q. What is an angularjs directive?

What it is (see the clear definition of jQuery as an example)?

A directive is essentially a function that executes when the Angular compiler finds it in the DOM. The function(s) can do almost anything, which is why I think it is rather difficult to define what a directive is. Each directive has a name (like ng-repeat, tabs, make-up-your-own) and each directive determines where it can be used: element, attribute, class, in a comment.

 A directive normally only has a (post)link function. A complicated directive could have a compile function, a pre-link function, and a post-link function.

What practical problems and situations is it intended to address?

The most powerful thing directives can do is extend HTML. Your extensions are a Domain Specific Language (DSL) for building your application. E.g., if your application runs an online shopping site, you can extend HTML to have “shopping-cart”, “coupon”, “specials”, etc. directives — whatever words or objects or concepts are more natural to use within the “online shopping” domain, rather than “div”s and “span”s (as @WTK already mentioned).

Directives can also componentize HTML — group a bunch of HTML into some reusable component. If you find yourself using ng-include to pull in lots of HTML, it is probably time to refactor into directives.

What design pattern does it embody, or alternatively, how does it fit into the purported MVC/MVW mission of angularjs

Directives are where you manipulate the DOM and catch DOM events. This is why the directive’s compile and link functions both receive the “element” as an argument. You can

  • define a bunch of HTML (i.e., a template) to replace the directive
  • bind events to this element (or its children)
  • add/remove a class
  • change the text() value
  • watch for changes to attributes defined in the same element (actually it is the attributes’ values that are watched — these are scope properties, hence the directive watches the “model” for changes)

In HTML we have things like <a href=”…”>, <img src=”…”>, <br>, <table><tr><th>. How would you describe what a, href, img, src, br, table, tr, and th are? That’s what a directive is.

Q. Filtering on object map rather than array in AngularJS

I would change my data structure to an array. Anyway, here’s another implementation to filter your friends object.

Skip code block

.filter(‘friendFilter’, function(utils){

return function(input, query){
if(!query) return input;
var result = [];

angular.forEach(input, function(friend){
if(utils.compareStr(friend.name, query) ||
utils.compareStr(friend.phone, query))
return result;

This iterates over the object only once, compares by name and phone and can be called like this.

<li ng-repeat=”friend in friends | friendFilter:query”>

I defined the compareStr in another module, but you don’t really need to do it.

angular.module(‘utils’, [])
.factory(‘utils’, function(){
compareStr: function(stra, strb){
stra = (“” + stra).toLowerCase();
strb = (“” + strb).toLowerCase();
return stra.indexOf(strb) !== -1;

Don’t forget to inject the filters module into your app


Here’s the full example: http://jsbin.com/acagag/5/edit

Q. How to cancel an $http request in AngularJS?

This feature was added to the 1.1.5 release via a timeout parameter:

var canceler = $q.defer();
$http.get(‘/someUrl’, {timeout: canceler.promise}).success(successCallback);
// later…
canceler.resolve();  // Aborts the $http request if it isn’t finished.

Q. Angular ng-click event delegation

It seems angular doesn’t do event delegation with repeaters. Someone opened an issue on github about it. The argument is if it actually leads to better performance.

There might be a workaround but it would require jQuery. It consists of creating a special directive to be used on a parent element and register the listener on its dom node.

Here’s an example, that is passed a function name to be called when a children node is clicked, and is also passed a selector to help identify which children nodes to listen to. Since angular’s jquery implementation only gives us the bind method – which is limited to registering event listeners to the actual element – we need to load jQuery to have access to either the on or delegate method.


<ul click-children=’fun’ selector=’li’>
<li ng-repeat=”s in ss” data-index=”{{$index}}”>{{s}}</li>

The function defined is defined in the controller and it expects to be passed an index

$scope.fun = function(index){
console.log(‘hi from controller’, index, $scope.ss[index]);

The directive uses $parse to convert an expression into a function that will be called from the event listener.

Skip code block

app.directive(‘clickChildren’, function($parse){
return {
restrict: ‘A’,
link: function(scope, element, attrs){
var selector = attrs.selector;
var fun = $parse(attrs.clickChildren);
element.on(‘click’, selector, function(e){
// no need to create a jQuery object to get the attribute
var idx = e.target.getAttribute(‘data-index’);

Plunker: http://plnkr.co/edit/yWCLvRSLCeshuw4j58JV?p=preview

Note: Functions can be delegated to directives using isolate scopes {fun: ‘&’}, which is worth a look, but this increases complexity.

Q: Conditionally change img src based on model data

Instead of src you need ng-src.

AngularJS views support binary operators

condition && true || false

So your img tag would look like this

<img ng-src=”{{interface == ‘UP’ && ‘green-checkmark.png’ || ‘big-black-X.png’}}”/>

plunker here (open dev tools to see the produced HTML)

0 Responses on AngularJS Interview Questions"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.