Prashanth Prashanth - 12 days ago 6
AngularJS Question

Image source is not binding with scope variable inside directive

In the below HTML, I want to inject 'src' value from scope variable in controller.

HTML :

<customdir filterby="name" src="imgName"></customdir>


The $scope.imgName variable in controller has the image path.

Javascipt :

var app = angular.module('myApp', []);

app.controller('myCtrl', function ($http, $scope) {

$scope.name = 'ready';
$scope.imgName = '~/Content/arrow-right-xxl.png';

)};

app.directive('customdir', function ($compile) {
var getTemplate = function (filter) {
switch (filter) {
case 'ready': return '<div class="col-lg-1" id="ready">' +
'<img src={{src}} style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' +
'</div>';
default: return '<input type="text" ng-model="filterby" />';
}
}
return {
restrict: 'E',
scope: {
src: '@',
filterby: "="
},
link: function (scope, element, attrs) {
var el = $compile(getTemplate(scope.filterby))(scope);
element.replaceWith(el);
}
};
});

Answer

Change your directive to this code

app.directive('customdir', function ($compile) {
    var getTemplate = function (filter, src) {
        switch (filter) {
            case 'ready': return '<div class="col-lg-1" id="ready">' +
                        '<img src='+src+' style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' +
                    '</div>';
            default: return '<input type="text" ng-model="filterby" />';           
        }
    }
    return {
        restrict: 'E',
        scope: {
            src: '=',
            filterby: "="
        },
        link: function (scope, element, attrs) {
            var el = $compile(getTemplate(scope.filterby, scope.src))(scope);
            element.replaceWith(el);
        }
    };
});

Passing scope.filterby and scope.src direct to your directive.