ngplayground
ngplayground

Reputation: 21627

AngularJS ngClick to fire a service but doesn't

I have the following inside a directive

scope.actions = {
    getSearch: searchResultPageService.getSearch(scope.keywords, scope.settings)
};

The template is as follows

<button class="btn btn-primary" type="button" data-ng-click="actions.getSearch()">Send</button>

In my service I'm only checking to see if the scope.keywords and scope.settings are passed through using a console.log but there is no output.

what am I doing wrong with my ngClick usage

(function () {

    'use strict';

    angular
        .module('app.search')
        .factory('searchResultPageService', [
            '$timeout',
            function ($timeout) {
                var $module = {

                    getSearch: function(keywords, settings){
                        console.log(keywords);
                        console.log(settings);

Upvotes: 1

Views: 39

Answers (2)

Nico
Nico

Reputation: 263

You are just affecting

searchResultPageService.getSearch(scope.keywords, scope.settings) 

result to

actions.getSearch

This is not a method, excepted if

searchResultPageService.getSearch(scope.keywords, scope.settings)

return a method - I've a little doubt -

Just try :

scope.actions = {
  getSearch: function() {
    searchResultPageService.getSearch(scope.keywords, scope.settings);
  }
};

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78545

scope.actions.getSearch is the result returned from calling searchResultPageService.getSearch, rather than the function itself.

You either need to pass the reference to that function to the view:

scope.actions = {
    getSearch: searchResultPageService.getSearch
};

And modify your view's click handler as follows:

<button class="btn btn-primary" type="button" data-ng-click="actions.getSearch(keywords, settings)">Send</button>

Or create a new anonymous function which is sent to the view:

scope.actions = {
    getSearch: function() {
        searchResultPageService.getSearch(scope.keywords, scope.settings);
    }
};

In which case your view code stays the same. Personally I would choose the second option there.

Upvotes: 2

Related Questions