Ricardo García Ricardo García - 5 months ago 18
AngularJS Question

Trying to pass jQuery plugin callback function to a controller function using a directive

i'm using a jQuery plugin that implements some callbacks which I would like to use. I'm trying to send the callback function directly to the controller but the parameters are not sending properly.

Here's my code

flairApp.directive('fullpage', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).fullpage({
afterLoad: function(anchorLink, index){
scope.afterLoad(anchorLink, index)
}
});
}
};
});


and for the controller

angular.module('homeController', ['ngSanitize'])

.controller('homeController', function($scope, Blog, $stateParams) {

$scope.afterLoad = function (anchorLink, index) {
console.log(anchorLink);
};

});


The html has the directive alone

<div fullpage></div>


It could be awesome if I could call the function using the directive instead like this:

<div fullpage after-load="afterload"></div>


Thanks in advance.

Answer

$(element).fullpage() takes an options object as its argument. In this options object, you have some options, like afterLoad. The function you pass to afterLoad is executed as a callback somewhere inside fullpage's stuff.

You can pass in a function to your directive with something like this in your directive defintion:

scope: {
  afterLoadCallback: '&' // this value is attached to scope.afterLoadCallback
}

The '&' means we're wanting to pass in a function. There are also '@' and '=' and they all behave slightly differently.

So...

flairApp.directive('fullpage', function() {
    return {
        restrict: 'A',
        scope: {
          afterLoadCallback: '&' // this value is attached to scope.afterLoad
        },
        link: function(scope, element, attrs) {
            $(element).fullpage({
                afterLoad: scope.afterLoadCallback // comes from function passed into directive in the view
            });
        }
    };
});

and in your view:

<div fullpage after-load-callback="foo()"></div> where foo is on the scope of the controller that controls the view where fullpage is being used.

Comments