AngularJS 在控制器中处理来自指令的事件

AngularJS handle event from directive in controller

我有以下 AngularJS 指令(在底部),如果单击 link saveClick() 则警报 window应该显示:

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

但是没有任何反应。有谁知道我做错了什么?

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>';
            ...

您需要向指令定义对象添加一个 link 函数,警报才能起作用。

下面是示例代码:

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