假设我有一个 指令 :
<component>
<img ng-src='{{something}}' />
</component>
定义为:
app.directive("component", function() {
return {
scope: {},
restrict: 'E',
transclude: true,
template: "<a href='' ng-click='MyService.doThings()' ng-transclude></a>"
}
});
尽管我付出了所有努力,但我还是不明白如何完成两项任务:
MyService
? (想想灯箱包装)更新解决方案:
app.directive("component", function(LightboxService) {
return {
restrict: 'E',
transclude: true,
replace: true,
template: "<a href='' ng-click='lb()' ng-transclude></a>",
link: function (scope, element, attrs) {
scope.lb = function () {
var src = $(element).find("img").attr("src");
LightboxService.show(src);
}
}
}
});
最佳答案
在下面检查您的指令:
app.directive("component", function() {
return {
scope: {
ngSrc: "@", //Text Binding
},
controller: function($scope, MyService) {
$scope.doThings = function() {
MyService.doThings();
}
},
restrict: 'E',
transclude: true,
template: "<a href='{{ng-src}}' ng-click='doThings' ng-transclude></a>"
}
});
您可以在此处了解有关具有隔离范围的指令的更多信息:
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
关于angularjs - 从指令模板调用服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685788/