简体   繁体   中英

Bind angular directive template to a event

I have a angular directive with a template like this

<Button id="testBtn">Test me<button>

I then have a directive controller where i have my API functions for the directive. I now need to pass a event to the calling module that the button was clicked.So that i can define what to do on the button click in my base application.

Something like this must go in the baseApp controller.

$scope.myDirective = {
    btnClick:function(){
     //define the function here
    }
}

My html template would look something like this

<my-simpledirective='myDirective'></my-simpledirective>

I have got to the part where i can declare my configurations in the $scope.myDirective = {} , but how can i do event definition there ?

FYI: This is the way kendoUI is doing it , want to do it in the same way.

Something like this would also be acceptable

<my-simpledirective='myDirective' btn-clicked="myCustomClick"></my-simpledirective>

then in the baseApp controller

$scope.myCustomClick = function(){
 //called when click event received
}

You could set up scope two-way binding to configuration object from controller:

app.directive('mySimpledirective', function() {
    return {
        scope: {
            config: '='
        },
        template: '<Button id="testBtn">{{config.label}}</button>',
        link: function(scope, element) {
            element.on('click', function(e) {
                scope.config.btnClick(e);
            });
        }
    };
});

and pass it in template as follows:

<my-simpledirective config='myDirective'></my-simpledirective>

Demo: http://plnkr.co/edit/ue8EX9OR17iQxIi1ekco?p=preview

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