ng-src in AngularJS

Definition and Usage

The ng-src directive overrides the original src attribute of an element.
The ng-src directive should be used instead of src if you have AngularJS code inside the src value.
The ng-src directive makes sure the image is not displayed wrong before AngularJS has evaluated the code.
<img ng-src="string"></img>
Lets understand ng-src using an example
1.   Create a project in visual studio and add a script.js file then give it a name like controller.js, later add a folder to this project and give it name as Images, add an image to “Images” folder and write the following code to the controller.js class
 /// <  reference path="angular.min.js" />
var myApp = angular.module('MyModule', []);
   myApp.controller("myController", function ($scope) {
                    var details = {
                        Name: "Angular JS Pic",                      
                        Picture: "/Images/angular.jpg"
                    $scope.details = details;
2.    Now add a HTML file to this project and give it name as “Index.html” and write the following code in this html file
<!doctype html>
<html ng-app="MyModule">

    <script src="Scripts/angular.min.js"></script>   
    <script src="Scripts/Controller.js"></script>

    <div ng-controller="myController">
            Image Name : {{ details.Name }}
            <img ng-src="{{details.Picture}}"
                 alt="{{ details.Name + 'Picture' }}"
                 style="height:90px; width:200px" />


   Now write run your application and see the output


Share this

Related Posts

Next Post »