ssougnez
ssougnez

Reputation: 5886

Using bound function in AngularJS directive in the link function

I'm writing a directive and it looks like this :

return {
    restrict: 'E',
    replace: false,
    scope: {
        getl: '&'
    },
    template: function()
    {
        return '<div data-ng-click="load_page(1)"></div>';
    },
    link: function(scope)
    {
        scope.current_page = 1;

        scope.load_page = function(increment)
        {
            scope.current_page += increment;

            scope.getl(scope.current_page);
        }
    }
};

I'm calling this directive like this:

<pager list="events" max="max_page" getl="get_events()"></pager>

What I'd like to do is being able to call the "getl" function from the "link" function of my directive but when I do so, I get the following error:

TypeError: Cannot use 'in' operator to search for 'f_get_events' in 2

I guess I'm missing something here but the only examples I found on Google were using the function in the template and I'd rather not to do like this.

Thanks for your help

Upvotes: 0

Views: 48

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

First thing your template function is missing " that may not be the problem but you should fix it, also your load_page is expecting increment parameter. As you passed nothing from ng-click function while calling load_page method, this line scope.current_page += increment; the value of current page becomes undefined because 1 + undefined = undefined

template: function()
{
    return '<div data-ng-click="load_page(1)"></div>';
},

Controller

scope.load_page = function(increment) {
    scope.current_page += increment;
    scope.getl({ curPage: scope.current_page});
}

Markup

<pager list="events" max="max_page" getl="get_events(curPage)"></pager>

Upvotes: 1

James Henry
James Henry

Reputation: 844

There are a few things going on here:

  • Your template is a broken string because you are using a single quote after load_page and no closing single string after the closing div:

    template: function() { return '<div data-ng-click="load_page()'></div>; },

  • You can call scope methods in directives like this:

    • Pass in a parameter to the get_events() call: <pager list="events" max="max_page" getl="get_events( currentPage )"></pager>
    • Then use the parameter in the directive code by passing in an object with a property which corresponds to the parameter name:

    scope.load_page = function(increment) { scope.current_page += increment; scope.getl({ currentPage: scope.current_page }); }

The type error you have given is hard to interpret, because it is hard to know if it is just because of the template string issue I described above, or something else.

Upvotes: 1

Related Questions