Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 895
Tomek Buszewski Avatar asked Aug 06 '26 18:08

Tomek Buszewski


1 Answers

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
}
like image 114
dotnetom Avatar answered Aug 09 '26 08:08

dotnetom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!