AngularJS:评估templateUrl函数中的表达式

时间:2015-08-21 08:43:17

标签: javascript angularjs angularjs-scope

我对angularjs很新,但我现在正在尝试做一些事情:)。我写了第一个简易指令,如:

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

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

我会称之为: <icon icon="home"></icon>效果很好。它包括所需的。 img/icons/home.svg

但如果我尝试将它绑定到范围变量,它就不会工作

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

给出输出:

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

我错过了什么吗?

感谢您的想法!

3 个答案:

答案 0 :(得分:1)

我更喜欢这样做:

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">'
    }
});

答案 1 :(得分:0)

尝试使用指令范围的icon变量。如下 -

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

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

答案 2 :(得分:0)

@Vishnu Atrai很接近: 始终尝试使用隔离范围

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