简体   繁体   中英

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)

<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>

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM