Skip to content

How do I get $emit to controller from directive built html

I’m having difficulty figuring this out. I have a directive building html from promise data. For each row, it’s adding buttons for CRUD operations. I do not know how to get the button event to trigger in my controller. Regardless of how my controller is set up, how can I get the event to register in my controller? I am currently trying $emit, but nothing seems to happen.

Directive generated html:

controls = controls+'<button type="button" data-tooltip-placement="bottom" data-tooltip="''" ng-click="$emit(&apos;'+action.broadcaster+'&apos;,'+rowId+')" name="''" class="btn btn-xs btn-default ng-scope"><i class="'+action.icon+'"></i> </button>'

How it looks in Chrome tools:

<button type="button" data-tooltip-placement="bottom" data-tooltip="delete" ng-click="$emit('removeOrgCourse',134)" name="delete" class="btn btn-xs btn-default ng-scope"><i class="fa fa-trash-o"></i> </button>

and my controller listener:

$scope.$on('removeOrgCourse', function( event, data ){

Just changed the ng-click to console.log("click") and nothing happened. So the issue is that ng-click is not registering;



While you can use events in angular to achive that, one other option is to use & expression scope binding to pass controller method to directive. Example code (from working code at jsbin):

<div ng-app="phoneApp">
<!-- we've replaced the use of $scope with the preferred "controller as" syntax. see: -->
<div ng-controller="AppCtrl as appctrl">
    <div phone dial="appctrl.callHome(message)"></div>
    <div phone dial="appctrl.callHome(message)"></div>
    <div phone dial="appctrl.callHome(message)"></div>


    app.controller("AppCtrl", function() {
        var appctrl = this;
        appctrl.callHome = function(message) {

And directive:

 app.directive("phone", function() {
        return {
            scope: {
                dial: "&"
            template: '<input type="text" ng-model="value">' +
              '<div class="button" ng-click="dial({message:value})">Call home!</div>'