EzDevInfo.com

angularjs interview questions

Top angularjs frequently asked interview questions

How to access the $scope variable in browser's console using AngularJS?

I would like to access my $scope variable in Chrome's JavaScript console. How do I do that?

I can neither see $scope nor the name of my module myapp in the console as variables.


Source: (StackOverflow)

How does data binding work in AngularJS?

How does data binding work in the AngularJS framework?

I haven't found technical details on their site. It's more or less clear how it works when data is propagated from view to model. But how does AngularJS track changes of model properties without setters and getters?

I found that there are JavaScript watchers that may do this work. But they are not supported in Internet Explorer 6 and Internet Explorer 7. So how does AngularJS know that I changed for example the following and reflected this change on a view?

myobject.myproperty="new value";

Source: (StackOverflow)

Advertisements

AngularJS : What is the difference between '@' and '=' in directive scope

I've read the AngularJS documentation on the topic carefully, and then fiddled around with a directive. Here's the fiddle.

And here are some relevant snippets:

  • from the html:

    <pane bi-title="title" title="{{title}}">{{text}}</pane>
    
  • from the pane directive:

    scope: { biTitle: '=', title: '@', bar: '=' },
    

There are several things I don't get:

  • why do I have to use "{{title}}" with '@' and "title" with '='?
  • can I also access the parent scope directly, without decorating my element with an attribute?
  • The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

I found another fiddle that shows the expression solution too: http://jsfiddle.net/maxisam/QrCXh/


Source: (StackOverflow)

What's the difference between ng-model and ng-bind

I'm currently learning angularjs and am having difficulty understanding the difference between ng-bind and ng-model.

Can anyone tell me how they differ and when one should be used over the other?


Source: (StackOverflow)

What is the best way to conditionally apply a class?

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex. What would be the best way to add a class to the li with the index selectedIndex in AngularJS?

I am currently duplicating (by hand) the li code and adding the class to one of the li tags and using ng-show and ng-hide to show only one li per index.


Source: (StackOverflow)

if else statement in AngularJS templates

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.

I want to make a condition like this:

if video.yt$aspectRatio equals widescreen then 
    element's attr height="270px"
else
    element's attr height="360px"

I'm iterating the videos using ng-repeat. Have no idea what should I do for this condition:

  • Add a function in the scope?
  • Do it in template?

Source: (StackOverflow)

angular.service vs angular.factory

I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service anywhere in official documentation.

What is the difference between the two methods? Which should be used for what (assuming they do different things)?


Source: (StackOverflow)

Combating AngularJS executing controller twice

I understand AngularJS runs through some code twice, sometimes even more, like $watch events, constantly checking model states etc.

However my code:

function MyController($scope, User, local) {

var $scope.User = local.get(); // Get locally save user data

User.get({ id: $scope.User._id.$oid }, function(user) {
  $scope.User = new User(user);
  local.save($scope.User);
});

//...

Is executed twice, inserting 2 records into my DB. I'm clearly still learning as I've been banging my head against this for ages!


Source: (StackOverflow)

How to use a filter in a controller?

I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller?

This is what I've tried so far:

function myCtrl($scope,filter1)
{ 
    // i simply used the filter function name, it is not working.
}

Source: (StackOverflow)

AngularJS: Service vs provider vs factory

What are the differences between AngularJS module's Service, Provider and Factory?


Source: (StackOverflow)

What's the correct way to communicate between controllers in AngularJS?

What's the correct way to communicate between controllers?

I'm currently using a horrible fudge involving window:

function StockSubgroupCtrl($scope, $http) {
    $scope.subgroups = [];
    $scope.handleSubgroupsLoaded = function(data, status) {
        $scope.subgroups = data;
    }
    $scope.fetch = function(prod_grp) {
        $http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
    }
    window.fetchStockSubgroups = $scope.fetch;
}

function StockGroupCtrl($scope, $http) {
    ...
    $scope.select = function(prod_grp) {
        $scope.selectedGroup = prod_grp;
        window.fetchStockSubgroups(prod_grp);
    }
}

Source: (StackOverflow)

Why does angularjs include an empty option in select

I've been working with angular for the last few weeks and the one thing which is really bothering me is that even after trying all permutations or the configuration defined in the spec at http://docs.angularjs.org/api/ng.directive:select, I still get an empty option as the first child of select element.

Here's the Jade

select.span9(ng-model='form.type', required, ng-options='option.value as option.name for option in typeOptions');

Here the controller

$scope.typeOptions = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement' }
];

Finally, here's the HTML which gets generated

<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" class="span9 ng-pristine ng-invalid ng-invalid-required">
    <option value="?" selected="selected"></option>
    <option value="0">Feature</option>
    <option value="1">Bug</option>
    <option value="2">Enhancement</option>
</select>

What do I need to do to get rid of it?

P.S. Things work without this as well, but it just looks odd if you use select2 without multiple selection.


Source: (StackOverflow)

Can one controller call another?

Is it possible to have one controller use another?

For example:

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>

    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

The controller file contains the following code:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

Which simply prints the current date;

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl, how would one go about doing this? The DI framework seems to be concerned with XmlHttpRequests and accessing services.


Source: (StackOverflow)

Redirecting to a certain route based on condition

I'm writing a small AngularJS app that has a login view and a main view, configured like so:

$routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
 .otherwise({redirectTo: '/login'});

My LoginController checks the user/pass combination and sets a property on the $rootScope reflecting this:

function LoginController($scope, $location, $rootScope) {
 $scope.attemptLogin = function() {
   if ( $scope.username == $scope.password ) { // test
        $rootScope.loggedUser = $scope.username;
        $location.path( "/main" );
    } else {
        $scope.loginError = "Invalid user/pass.";
    }
}

Everything works, but if I access http://localhost/#/main I end up bypassing the login screen. I wanted to write something like "whenever the route changes, if $rootScope.loggedUser is null then redirect to /login"

...

... wait. Can I listen to route changes somehow? I'll post this question anyway and keep looking.


Source: (StackOverflow)

AngularJS : How to bind to list of checkbox values?

I have a few checkboxes:

<input type='checkbox' value="apple" checked>
<input type='checkbox' value="orange">
<input type='checkbox' value="pear" checked>
<input type='checkbox' value="naartjie">

That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values e.g. ['apple', 'pear'].

ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.

Is there another way to do it so that I can bind the four checkboxes to a list in the contrller?


Source: (StackOverflow)