denkweite
denkweite

Reputation: 1063

AngularJS: Evaluating expressions in templateUrl function

I am pretty new to angularjs but I am now trying to do some things :). I wrote a first easy directive like:

angular.module('coc')
  .directive('icon', function() {

    return {
      restrict: 'E',
      scope: true,
      templateUrl: function(element, attributes) {
        return 'img/icons/' + attributes.icon + '.svg';
      }
    }
  });

I'm gonna call it like: <icon icon="home"></icon> which works pretty well. It includes as desired. img/icons/home.svg

But if I try to bind it to a scope variable it won`t work

Try to include icon: {{icon}}
<icon icon="{{icon}}"></icon>

Gives the output:

Try to include icon: home
(console.log): Error: [$compile:tpload] Failed to load template: img/icons/{{icon}}.svg (HTTP status: 404 Not Found)

Am I missing something?

Thanks for your ideas!

Upvotes: 1

Views: 509

Answers (3)

michelem
michelem

Reputation: 14590

I'd prefer to do something like this:

HTML:

<div ng-app="myApp" ng-controller="dummy">
    <icon icon="icon"></icon>
</div>

JS:

angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
    $scope.icon = 'home';
}])
.directive('icon', function () {
    return {
        restrict: 'E',
        scope: {icon: '='},
        template: '<img ng-src="img/icons/{{icon}}.svg">'
    }
});

Upvotes: 1

ThibaudL
ThibaudL

Reputation: 1009

@Vishnu Atrai was close : Always try to use an isolated scope

return {
    restrict: 'E',
    scope: {
        icon: "="
    },
    template: '<img ng-src="img/icons/{{icon}}.svg">'
}

Upvotes: 0

Vishnu Atrai
Vishnu Atrai

Reputation: 2368

Try icon variable with directive scope. like below -

angular.module('coc')
  .directive('icon', function() {

    return {
      restrict: 'E',
      scope: {
        icon: "=icon"
      },
      templateUrl: function(element, attributes) {
        return 'img/icons/' + attributes.icon + '.svg';
      }
   }
 });

Upvotes: 0

Related Questions