Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Angular - running functions from controller on ng-click

I want to run some function on load of a directive, and then be able to "rerun" it again with ng-click. My code is as follows:

const app = angular.module('app', []);

class dummyController {
    logIt() {
        console.log('logging');
    }
}

app.directive('dummyDir', () => {
    return {
        controller: dummyController,
        link(scope, element, attrs, ctrl) {
            scope.logIt = ctrl.logIt();
            scope.logIt;

        }
    };
});

HTML

<div ng-app="app">
    <button class="reinit" type="submit" dummy-dir ng-click="logIt()">Reinit</button>
</div>

CodePen

Unfortunately, clicking the button does nothing. What have I done wrong?

Upvotes: 3

Views: 87

Answers (2)

Kunal Navhate
Kunal Navhate

Reputation: 108

class dummyController {
    logIt() {
        console.log('logging');
    }
    logIt();

}

Upvotes: -1

dotnetom
dotnetom

Reputation: 24901

In this line

scope.logIt = ctrl.logIt();

you are actually invoking the logIt function and assigning the result of this function to variable logIt. The function does not return anything, so the result is undefined.

Instead you need to assign variable a pointer to a function, so you can use it later:

link(scope, element, attrs, ctrl) {
    scope.logIt = ctrl.logIt;    // assign a function, do not invoke it
    scope.logIt();               // invoke the function
}

Upvotes: 4

Related Questions