Sunday, October 9, 2016

AngularJS - Directive - "ng-src"

Directive ng-src is the replacement for the HTML src attribute. 

Let's take this example:
var myApp = angular.module('myApp', [])
                                         .controller('myController', function($scope){
                                                 var employee = {
                                                       firstName: Pratibha,
                                                       lastName: Hyanki,
                                                       image: '/Images/pratibha.png'
                                                  };

                                                $scope.employee = employee;
                                          });
Using this controller:
     <div ng-controller='myCOntroller'>
              <div>
                    First Name:  {{employee.firstName}}
              </div>                   
              <div>
                    Last Name: {{employee.lastName}}
              </div>
             <div>
                     <img src={{employee.image}} />
              <div>         
    </div>

When a AngularJS binding expression is being used for src attribute there are two calls made to the server. First one when the DOM is getting loaded a request to the server is made for the src attribute value, since at this time the AngularJS binding expression which is associated with the attribute is not evaluated so it uses the angular expression as the path (including curly braces) which is not a valid path. It gives the error 404 not found which is visible when we launch the developer tools. 

The correct image is shown on the UI because the second request is made to to the server to load the image when Angular expression is getting evaluated.
       
To resolve the above issue ng-src directive is being used in place of src. It has two advantages, first there is only one request to load the image goes that to when  the binding expression is getting evaluated. Second only one request for loading the image is going the 404 error doesn't appear.

No comments:

Post a Comment