user5638730 user5638730 - 5 months ago 8
AngularJS Question

Angular define own directive

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.

Answer

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