J D
J D

Reputation: 1818

Callback and AngularJS (ng-click)

I have a a button like

<div class="button" ng-repeat="event in events" 
    ng-click="selectEvent($index, event, generate)">
 Content
</div>

In which generate is supposed to be the callback function, however for some reason it is undefined when called.

Like when someone clicks on the button, I get TypeError: undefined is not a function. Where my selectEvent() code looks like

$scope.selectEvent = function ($index, event, callback) {
    // Do some stuff with $index and event

    console.log(callback); // This is undefined
    callback($scope, $http);
};

and function generate() is defined somewhere in the JS file.

Upvotes: 1

Views: 6333

Answers (3)

Ben Lesh
Ben Lesh

Reputation: 108491

Preface: @MaximShoustin's answer is correct. However, I'm not sure it addresses some of the other problems with what's going on here.

Also, I don't want this to sound condescending at all, it's just constructive criticism. Take it or leave it.

The wiring up of callbacks should probably be done by your controller, rather than your view.

Why?

  1. It's harder to test the controller if the callback is wired by your view.
  2. It's "business logic".
  3. The view should just be concerned with displaying things and wiring up events.

It looks like you're trying to wire up business logic in your view. In other words you're saying "when you click this thing, call this function, then call this other function when you're done".

$scope.doSomething = function($index, event) {
    //do stuff
    $scope.generate();
};

$scope.generate = function (){
    //more stuff.
};

Why are you passing controller-scoped variables into a function that was passed into a function by an evaluated expression in an event binding? Seems convoluted.

I'm speaking specifically of this line:

callback($scope, $http);

What's the purpose here? Is it that "generate" is going to be different for each event? Why do you have to pass $scope and $http into it? You should have access to those throughout your controller function.

It seems like you're trying to do something crazy here. Perhaps I don't understand the problem you're trying to solve.

Upvotes: 5

AAA
AAA

Reputation: 1384

For this to work, generate needs to be in scope. The Angular template needs to be able to see it. So, you can define it in the controller:

$scope.generate = generate;

and that would assign your current generate function to be visible to Angular.

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Sounds like Angular doesn't see generate callback. Be sure that it defined into controller like:

$scope.generate = function(){/**/} 

or

$scope.generate = function(){
    generate();// if it defined out of scope 
} 

or

$scope.generate = generate;

Upvotes: 3

Related Questions