我对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)
我想念什么吗?
感谢您的想法!
最佳答案
我更喜欢做这样的事情:
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">'
}
});