EzDevInfo.com

angularjs-directive interview questions

Top angularjs-directive frequently asked interview questions

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)

How to set focus on input field?

What is the 'Angular way' to set focus on input field in AngularJS?

More specific requirements:

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal.
  2. Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

I tried to achieve the first requirement with autofocus, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).

Any help will be appreciated.


Source: (StackOverflow)

Advertisements

AngularJS : link vs compile vs controller

when you create a directive, you can put code into the compiler, the link function or the controller. In the docs they explain that:

  • compile and link function are used in different phases of the angular cycle
  • controllers are shared between directives.

However, for me it is not clear, which kind of code should go where. E.g.: I can create functions in compile and have them attached to the scope in link. Or I only attach functions to the scope in the controller? How are controllers shared between directives, if each directive can have its own controller? Are really the controllers shared or is it just the scope properties?

Thanks schacki


Source: (StackOverflow)

When to favor ng-if vs. ng-show/ng-hide?

I understand that ng-show and ng-hide affect the class set on an element and that ng-if controls whether an element is rendered as part of the DOM.

Are there guidelines on choosing ng-if over ng-show/ng-hide or vice-versa?


Source: (StackOverflow)

How do I implement the bootstrap navbar active class with Angular JS

If I have a navbar in bootstrap with the items

Home | About | Contact

How do I set the active class for each menu item when they are active? That is, how can I set class="active" when the angular route is at

  1. #/ for home
  2. #/about for the about page
  3. #/contact for the contact page

Source: (StackOverflow)

AngularJS : When writing a directive, how do I decide if a need no new scope, a new child scope, or a new isolate scope?

I'm looking for some guidelines that one can use to help determine which type of scope to use when writing a new directive. Ideally, I'd like something similar to a flowchart that walks me though a bunch of questions and out pops the correct answer – no new new scope, new child scope, or new isolate scope – but that is likely asking for too much. Here's my current paltry set of guidelines:

  • don't use an isolate scope if the element that will use the directive uses ng-model
    See ngModel and component with isolated scope and
    Why formatters does not work with isolated scope?
  • if the directive doesn't modify any scope/model properties, don't create a new scope
  • isolate scopes seem to work well if the directive is encapsulating a set of DOM elements (the docs say "a complex DOM structure") and the directive will be used as an element, or with no other directives on the same element

I'm aware that using a directive with an isolate scope on an element forces all other directives on that same element to use the same (one) isolate scope, so doesn't this severely limit when an isolate scope can be used?

I am hoping that some from the Angular-UI team (or others that have written many directives) can share their experiences.

Please don't add an answer that simply says "use an isolate scope for reusable components".


Source: (StackOverflow)

How to use a keypress event in AngularJS?

I want to catch the enter key press event on the textbox below. To make it more clear I am using a ng-repeat to populate the tbody. Here is the HTML:

<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield" 
    data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>

This is my module:

angular.module('components', ['ngResource']);

I am using a resource to populate the table and my controller code is:

function Ajaxy($scope, $resource) {
//controller which has resource to populate the table 
}

If there is anymore info needed, please comment.


Source: (StackOverflow)

How to call a method defined in an AngularJS directive?

I have a directive, here is the code :

.directive('map', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function($scope, element, attrs) {

            var center = new google.maps.LatLng(50.1, 14.4); 
            $scope.map_options = {
                zoom: 14,
                center: center,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            // create map
            var map = new google.maps.Map(document.getElementById(attrs.id), $scope.map_options);
            var dirService= new google.maps.DirectionsService();
            var dirRenderer= new google.maps.DirectionsRenderer()

            var showDirections = function(dirResult, dirStatus) {
                if (dirStatus != google.maps.DirectionsStatus.OK) {
                    alert('Directions failed: ' + dirStatus);
                    return;
                  }
                  // Show directions
                dirRenderer.setMap(map);
                //$scope.dirRenderer.setPanel(Demo.dirContainer);
                dirRenderer.setDirections(dirResult);
            };

            // Watch
            var updateMap = function(){
                dirService.route($scope.dirRequest, showDirections); 
            };    
            $scope.$watch('dirRequest.origin', updateMap);

            google.maps.event.addListener(map, 'zoom_changed', function() {
                $scope.map_options.zoom = map.getZoom();
              });

            dirService.route($scope.dirRequest, showDirections);  
        }
    }
})

I would like to call updateMap() on a user action. The action button is not on the directive.

What is the best way to call updateMap() from a controller?


Source: (StackOverflow)

What is ng-transclude?

I have seen a number of questions on StackOverflow discussing ng-transclude, but none explaining in layman's terms what it is.

The description in the documentation is as follows:

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

This is fairly confusing. Would someone be able to explain in simple terms what ng-transclude is intended to do and where it might be used?


Source: (StackOverflow)

How to access parent scope from within a custom directive *with own scope* in AngularJS?

I'm looking for any manner of accessing the "parent" scope within a directive. Any combination of scope, transclude, require, passing in variables (or the scope itself) from above, etc. I'm totally willing to bend over backwards, but I want to avoid something totally hacky or unmaintainable. For example, I know I could do it right now by taking the $scope from the preLink parameters and iterating over it's $sibling scopes to find the conceptual "parent".

What I really want is to be able to $watch an expression in the parent scope. If I can do that, then I can accomplish what I'm trying to do over here: AngularJS - How to render a partial with variables?

An important note is that the directive must be re-usable within the same parent scope. Therefore the default behavior (scope: false) doesn't work for me. I need an individual scope per instance of the directive, and then I need to $watch a variable that lives in the parent scope.

A code sample is worth 1000 words, so:

app.directive('watchingMyParentScope', function() {
    return {
        require: /* ? */,
        scope: /* ? */,
        transclude: /* ? */,
        controller: /* ? */,
        compile: function(el,attr,trans) {
            // Can I get the $parent from the transclusion function somehow?
            return {
                pre: function($s, $e, $a, parentControl) {
                    // Can I get the $parent from the parent controller?
                    // By setting this.$scope = $scope from within that controller?

                    // Can I get the $parent from the current $scope?

                    // Can I pass the $parent scope in as an attribute and define
                    // it as part of this directive's scope definition?

                    // What don't I understand about how directives work and
                    // how their scope is related to their parent?
                },
                post: function($s, $e, $a, parentControl) {
                    // Has my situation improved by the time the postLink is called?
                }
            }
        }
    };
});

Source: (StackOverflow)

Add directives from directive in AngularJS

I'm trying to build a directive that takes care of adding more directives to the element it is declared on. For example, I want to build a directive that takes care of adding datepicker, datepicker-language and ng-required="true".

If I try to add those attributes and then use $compile I obviously generate an infinite loop, so I am checking if I have already added the needed attributes:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        element.attr('datepicker', 'someValue');
        element.attr('datepicker-language', 'en');
        // some more
        $compile(element)(scope);
      }
    };
  });

Of course, if I don't $compile the element, the attributes will be set but the directive won't be bootstrapped.

Is this approach correct or am I doing it wrong? Is there a better way to achieve the same behavior?

UDPATE: given the fact that $compile is the only way to achieve this, is there a way to skip the first compilation pass (the element may contain several children)? Maybe by setting terminal:true?

UPDATE 2: I have tried putting the directive into a select element and, as expected, the compilation runs twice, which means there is twice the number of expected options.


Source: (StackOverflow)

AngularJS : When to use transclude 'true' and transclude 'element'?

When should I use transclude: 'true' and when transclude: 'element' ? I cant find anything about transclude: 'element' in the angular docs, they are pretty confusing.

I would be happy if someone could explain this in simple language. What is the benefit of each option? What is the real difference between them?

This is what I have found :

transclude: true

Inside a compile function, you can manipulate the DOM with the help of transclude linking function or you can insert the transcluded DOM into the template using ngTransclude directive on any HTML tag.

and

transclude: ‘element’

This transcludes the entire element and a transclude linking function is introduced in the compile function. You can not have access to scope here because the scope is not yet created. Compile function creates a link function for the directive which has access to scope and transcludeFn lets you touch the cloned element (which was transcluded) for DOM manipulation or make use of data bound to scope in it. For your information, this is used in ng-repeat and ng-switch.


Source: (StackOverflow)

What is the best way to conditionally apply attributes in Angular?

I need to be able to add for example "contenteditable" to elements, based on a boolean variable on scope.

Example use:

<h1 attrs="{'contenteditable=\"true\"': editMode}">{{content.title}}</h1>

Would result in contenteditable=true being added to the element if $scope.editMode was set to true. Is there some easy way to implement this ng-class like attribute behavior? I'm considering writing a directive and sharing if not.

Edit: I can see that there seems to be some similarities between my proposed attrs directive and ng-bind-attrs, but it was removed in 1.0.0.rc3, why so?


Source: (StackOverflow)

Dynamically add directive in AngularJS

I have a very boiled down version of what I am doing that gets the problem across.

I have a simple directive. Whenever you click an element, it adds another one. However, it needs to be compiled first in order to render it correctly.

My research led me to $compile. But all the examples use a complicated structure that I don't really know how to apply here.

Fiddles are here: http://jsfiddle.net/paulocoelho/fBjbP/1/

And the JS is here:

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p>{{text}}</p>',
        scope: {
            text: '@text'
        },
        link:function(scope,element){
            $( element ).click(function(){
                // TODO: This does not do what it's supposed to :(
                $(this).parent().append("<test text='n'></test>");
            });
        }
    };
});

Solution by Josh David Miller: http://jsfiddle.net/paulocoelho/fBjbP/2/


Source: (StackOverflow)