3

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);
    }
};
});
Prashanth
  • 111
  • 1
  • 10

3 Answers3

1

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.

errorare
  • 178
  • 1
  • 1
  • 15
0

Pass the value of imgName like below, as you are using @ for src attribute of your directive.

HTML :

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

Use ng-src in the img tag like below:

Javascript:

var getTemplate = function (filter) {
    switch (filter) {
        case 'ready': return '<div class="col-lg-1" id="ready">' +
                '<img ng-src="{{src}}" style="height: 35px; width: 35px; margin-left: 0px; margin-top: 35px" />' +
                '</div>';
        default: return '<input type="text" ng-model="filterby" />';           
    }
}
Tajkia Rahman Toma
  • 472
  • 1
  • 5
  • 16
-1

Try this

<customdir filterby="name" ng-src="imgName"></customdir>
Sujithrao
  • 789
  • 3
  • 12
  • 27