[英]Angular - Using a controller function in directive
To start: I'm not having an error but try to optimize my code here. 开始:我没有错误,但是尝试在这里优化我的代码。
I have an application where in many cases an address will be shown. 我有一个在许多情况下会显示地址的应用程序。 This address should be editable in many cases.
在许多情况下,此地址应可编辑。 So I created a directive.
所以我创建了一条指令。
My directive 我的指令
app.directive('addressview', function(medipracticeData) {
return {
restrict: 'E',
templateUrl: 'address-view.html',
replace : true,
scope : {
address : '=',
editAddress : '&?'
},
controller : function($scope){
$scope.edit = function(){
$scope.editAddress( { address : $scope.address } );
}
}
};
});
My directive template (address-view.html) 我的指令模板(address-view.html)
<div ng-controller="AddressController as AddressCtrl">
<addressview
address="OfficeCtrl.office.address"
edit-address="AddressCtrl.showAddressEdit(address)">
</addressview>
</div>
As you can see, I am passing the AddressCtrl.showAddressEdit()
function in every directive... This is the function in my Address Controller, which triggers a popup in which I can edit the address. 如您所见,我在每个指令中传递了
AddressCtrl.showAddressEdit()
函数。这是我的地址控制器中的函数,它将触发一个弹出窗口,我可以在其中编辑地址。
My controller 我的控制器
app.controller("AddressController", AddressController);
AddressController.$inject = ["$scope"];
function AddressController($scope) {
var avm = this;
avm.showAddressEdit = showAddressEdit;
function showAddressEdit(address) {
console.log(address);
}
}
I'm trying to avoid passing this function AddressCtrl.showAddressEdit()
to my directive all the time. 我试图避免
AddressCtrl.showAddressEdit()
将此函数AddressCtrl.showAddressEdit()
传递给我的指令。 Is it possible to use this function within my directive controller? 是否可以在我的指令控制器中使用此功能? So that everytime I use this directive, it would be usable as following:
这样,每当我使用此指令时,它就可以按以下方式使用:
<div ng-controller="AddressController as AddressCtrl">
<addressview
address="OfficeCtrl.office.address">
</addressview>
</div>
You could use a Service, like this 您可以像这样使用服务
angular.module("myModule").service("myService", function(){
return {
showAddressEdit: function(address) {
console.log(address);
}
};
});
Then, you can inject it to your Controller in the directive/component like this: 然后,您可以将其注入到指令/组件中的控制器中,如下所示:
// ...
controller : function($scope, myService){
$scope.edit = function(){
$scope.editAddress( { address : $scope.address } );
}
$scope.showAdressEdit = myService.showAdressEdit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.