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)
<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.
My controller
app.controller("AddressController", AddressController);
AddressController.$inject = ["$scope"];
function AddressController($scope) {
var avm = this;
avm.showAddressEdit = showAddressEdit;
function showAddressEdit(address) {
console.log(address);
}
}
My question
I'm trying to avoid passing this function AddressCtrl.showAddressEdit() to my directive all the time. 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>
replace: trueattribute, which is deprecated. Don't use it anymore. Which angular version are you on? Also, you could use a component instead of a directive, check it out: componentscontrollerAssyntax, if you want to improve your code