我正在学习如何创建自定义指令。
我的服务看起来像这样:
myApp.service('myService',function(){
this.myFunction=function(myParam){
// do something
}
});
这是我的指令:
myApp.directive('myDirective',function(myService){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="myService.myFunction(param)">Do action</button>',
}
});
在HTML中,当我使用<my-directive my-param="something"></my-directive>
时,它会正确呈现为按钮。但是,当我点击它时,myService.myFunction
,并没有被执行。
我想我做错了什么。有人能指点我吗? 我想这与指令的范围有关。
答案 0 :(得分:1)
该服务无法直接在模板中使用。您必须使用附加到指令scope
的函数,并从此函数中调用服务函数。
myApp.directive('myDirective',function(myService){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="callService(param)">Do action</button>',
link: function(scope, element, attrs) {
scope.callService = function() {
myService.myFunction();
}
}
}
});
答案 1 :(得分:1)
它不起作用,因为在您的示例中,指令实际上并不知道什么是myService
。你必须明确注入它,例如:
myApp.directive('myDirective', ['myService', function(myService){ ... }]);
答案 2 :(得分:0)
您应该使用控制器进行所有DOM修改 请参阅此plunkr:https://plnkr.co/edit/HbfD1EzS0av5BG6NgtIv?p=preview
.directive('myFirstDirective', [function() {
return {
'restrict': 'E',
'controller': 'MyFirstController',
'controllerAs': 'myFirstCtrl',
'template': '<h1>First directive</h1><input type="text" ng-model="myFirstCtrl.value">'
};
}
答案 3 :(得分:-1)
您可以在控制器中注入服务,然后在模板中调用该函数:
将myService
注入控制器:
myApp.controller("ctrl", function($scope, myService) {
$scope.doService = function(myParam) {
return myService.myFunction(myParam);
};
});
在模板中调用控制器的doService
方法:
myApp.directive('myDirective',function(){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="doService(param)">Do action</button>',
}
});