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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With