0

I'm currently trying to define my own directive in Angular, which doesn't to more then a console.log(). What I tried was the following:

log.directive.js:

export default function () {
    return {
        bindToController: {
            val: '=log-dir'
        },
        controllerAs: '$ctrl',
        template: "",
        controller: function () {
            console.log("test");
        }
    };
}

Then I import the directive:

import logDirDirective from '../../directives/log.directive';

and add it to my module:

angular.module(MODULE_NAME).directive('log-dir',logDirDirective);

And then, in my HTML I try to use it as:

<div class="......" log-dir>
</div>

What I expected now, is to see test in my console after loading, but I don't. Where is the mistake?

PS: Please note that I'm relatively new to angular and completely new to selfmade directives, so my mistake might me very trivial.

1

1 Answer 1

1

Directive names and binding/scope config must conform to normalization conventions. It means that correct definition of the directive should be:

angular.module(MODULE_NAME).directive('logDir', logDirDirective);

And the same for bindings config:

bindToController: {
    val: '=logDir'
},

Check "AngularJs directive naming conventions" question for more detailed answer to why.

UPD.

Here is a demo of variations with @ and = bindings: http://plnkr.co/edit/mA0YnVhd7t241kdAvgRl?p=info

Sign up to request clarification or add additional context in comments.

10 Comments

This doesn't seem to change anything, I wonder why angulars directives would work then (like ng-click, etc..)
hold on, my bad... I also changed (intuitively) it in the html, but then realized, that there, everything has to stay the same (so log-dir). Now it works. Can you tell me, what I'd have to change to log a string, specified when I write the directive in HTML, so I can write div log-dir="special string"and then in console I can find that string?
According to your bindToController config, it binds attribute log-dir to controller property named val. So it means, you will be able to do console.log(this.val). But also note, that = means two-way data binding, i.e. it needs to be a valid Angular statement. If you want attribute to be just a string you should use directive like this log-dir="'special string'".
Hmm, somehow I'm getting undefined as value. I'm right, just changing console.log("test") to console.log(this.val) and then writing <div log-dir="another test"></div> right?
Got it, didn't have the single quotes for the string in my directive, thank you.
|

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.