Search code examples
angularjsangular-directive

Pass a function to a directive and then call it with parameters


I have a directive (show youtube video) that should take a function as an attribute to be able to launch it inside the link function.

Inside the html I wrote (in jade)

div(ng-controller="videoPageCtrl")
    ...
    div(my-youtube,id='aaa',url='KEHxHr-Ih9w',on-change="doEventsOnChange")

My controller and directive look as following

app
.directive('myYoutube', function($sce, $timeout) {
    return {
        restrict: 'A',
        scope: {
            url: '@',
            id: '@',
            onChange: '&',
        },
        link: function(scope) {
            $timeout(function() {
                scope.player = new YT.Player(scope.id, {
                    videoId: scope.url,
                    events: {
                        'onStateChange': function(state) {
                            console.log('state changed to', state, scope.id, scope.onChange);
                            scope.onChange(state, scope.id);
                        }
                    }
                });
            }, 5000);
        }
    };
})
.controller('videoPageCtrl', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
    $scope.doEventsOnChange = function(state, id) {
        console.log(id, state, 'launched from controller!');
    };
}]);

The problem is that I cannot pass id and state and fire up the doEventsOnChange function. In result in the chrome dev console I can only see the state changed to lines, but no launched from controller! lines with passed id and state.

What am I doing wrong?


Solution

  • You should use onChange: '&' when you want to use the function in your directive's template, use onChange: '=' if you just want to pass the function to the directive's scope.

    The & binding allows a directive to trigger evaluation of an expression in the context of the original scope, at a specific time. Any legal expression is allowed, including an expression which contains a function call. Because of this, & bindings are ideal for binding callback functions to directive behaviors.