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="'+action.name+'" ng-click="$emit(''+action.broadcaster+'','+rowId+')" name="'+action.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 ){ console.log(data); });
UPDATE:
Just changed the ng-click to console.log("click")
and nothing happened. So the issue is that ng-click is not registering;
Advertisement
Answer
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 egghead.io)(see working code at jsbin):
<div ng-app="phoneApp"> <!-- we've replaced the use of $scope with the preferred "controller as" syntax. see:http://toddmotto.com/digging-into-angulars-controller-as-syntax/ --> <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> </div>
Controller:
app.controller("AppCtrl", function() { var appctrl = this; appctrl.callHome = function(message) { alert(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>' }; });