AngularJS - pass function to directive

angularjs

Solution

To call a controller function in parent scope from inside an isolate scope directive, use `dash-separated` attribute names in the HTML like the OP said.

Also if you want to send a parameter to your function, call the function by passing an object:

<test color1="color1" update-fn="updateFn(msg)"></test>

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

Fiddle

Problem

I have a example angularJS ``` <div ng-controller="testCtrl"> <test color1="color1" updateFn="updateFn()"></test> </div> <script> angular.module('dr', []) .controller("testCtrl", function($scope) { $scope.color1 = "color"; $scope.updateFn = function() { alert('123'); } }) .directive('test', function() { return { restrict: 'E', scope: {color1: '=', updateFn: '&'}, template: "<button ng-click='updateFn()'>Click</button>", replace: true, link: function(scope, elm, attrs) { } } }); </script> </body> </html> ``` I want when I click button, the alert box will appear, but nothing show. Can anyone help me?

Original source