3

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?

1
  • If you call the logit() from within the controller, you don't need to call it from link. Doing that will call the log it() twice. The reason is that controller gets instanciated before link and also runs any logit() when controller is invoked. So invoke logit() from controller, make a different function that will run logit() invokation from ng-click Commented Dec 20, 2015 at 16:13

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.