Slimshadddyyy Slimshadddyyy - 2 months ago 6
Javascript Question

AngularJS - Display image using directive

Image Constants

angular.module('app-config', []).constant('imageConstant',
{
logoPath: 'assets/img/logo/',
faviconPath: 'assets/img/favicon/',
layoutPath: 'assets/img/layout/',
logoFileName: 'myLogo.png'
});


Directive

myApp.directive("streamingLogo", function () {

var linker = function (scope, element, attrs) {

//pass image constants here to append image url
//for ex: src = imageConstant.logoPath + imageConstant.logoFileName;

};
return {
restrict: "A",
link: linker
};
});


HTML

<img class="my-logo" id="my-logo" ng-src="{{src}}" streamingLogo/>



  • I have configured image url and file names in a constant file. How do
    I pass it in a directive to append image path and name dynamically so
    that the it gets displayed using above directive ?



The idea is to have a configuration file for image path and names so that in HTML, only
ng-src="{{src}}"
is passed instead of full absolute path.

Answer

Add imageConstant dependency to your directive and you are good to go, like this:

myApp.directive("streamingLogo", ['imageConstant', function(imageConstant) {
   var linker = function (scope, element, attrs) {

       scope.logoPath = imageConstant.logoPath; 
       scope.favIconPath = imageConstant.faviconPath;
       scope.layoutPath = imageConstant.layoutPath;
       scope.logoFileName = imageConstant.logoFileName;

   };
   return {
       restrict: "A",
       link: linker
   };
}]);