Search code examples
angularjsangular-directive

AngularJS handle event from directive in controller


I have the following AngularJS directive (at bottom) and if the link saveClick() is clicked then the alert window should be shown:

<span save-click="alert('hallo ich binssdsd')" data-ng-dropdown-multiselect options="vm.translatedRoles" selected-model="vm.selectedRoles" external-id-prop="label"></span>

but nothing happens. Does anyone know what I am doing wrong?

directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse', '$rootScope',
function ($filter, $document, $compile, $parse, $rootScope) {

    return {
        restrict: 'AE',
        scope: {
            selectedModel: '=',
            options: '=',
            extraSettings: '=',
            events: '=',
            searchFilter: '=?',
            translationTexts: '=',
            groupBy: '@',
            saveClick: '&'
        },
        template: function (element, attrs) {
            var checkboxes = attrs.checkboxes ? true : false;
            var groups = attrs.groupBy ? true : false;

            var template = '<div class="multiselect-parent btn-group dropdown-multiselect">';
            template += '<li><a data-ng-click="saveClick()"><span class="glyphicon glyphicon-floppy-disk"></span>  {{texts.save}}</a>';
            ...

Solution

  • You would need to add a link function to the directive definition object for the alert to work.

    Below is the sample code:

    directive.js

    var app = angular.module("myApp", [])
    
    app.directive('testAlert',function() {
      return {
         restrict: 'E',
         template: '<button ng-click="alertClick()">Test</button>',
         link: function (scope) {
            scope.alertClick = function () {
            alert('Welcome!');
         };
       }
      }
    });
    

    index.html

    <div ng-app="myApp">
       <test-alert></test-alert>
    </div>
    

    WorkingExample