steve steve - 15 days ago 7
AngularJS Question

Angular directive not compiling, failing silently

I tried to define my first directive in angular today. This is what it looks like:

app.js:

var frameApp = angular.module('frameApp', [
'ngRoute',
'frameServices',
'frameFilters',
'frameDirectives',
'frameControllers'
]);


console.log("1");
frameApp.directive('ngEnter', [function(){
console.log("2");
return {
link: function($scope, iElm, iAttrs, controller) {
console.log("3");
}
};
}]);


When I load the page I only see the "1" printed in the console.

it is used in the code like this:

<input
type="text"
placeholder="username"
ng-model="username"
ng-enter="createUser()">


my index.html looks like this:

<!DOCTYPE html>
<html ng-app="frameApp" ng-controller="PageCtrl">
<head>
<!-- lots of irrelevant scripts -->
<!-- config and initialization -->
<script type="text/javascript"
src="app/app.js">
</script>
<script type="text/javascript"
src="app/app.routes.js">
</script>

<title>{{ title }}</title>
</head>
<body>

<ng-include
src="'app/partials/header.html'"
onload="onHeaderLoaded()">
</ng-include>

<ng-include
src="'app/partials/loginbox.html'"
ng-if="loginVisible">
</ng-include>

<div id="content" ng-view></div>

</body>
</html>


I initially tried to get the directive from this question working: How to use a keypress event in angularjs

How do I find out why it doesn't work and fix it?

UPDATE

I found the problem, it was a second declaration of frameApp above my routes declaration. If you have a similar problem, check that you aren't overriding any modules because angular doesn't throw any errors if you do.

Answer

You should remove ''(blank) dependency injection which would throw an error, You need to replace frameApp.directive('ngEnter', ['', function(){ with frameApp.directive('ngEnter', [function(){

Directive

console.log("1");
frameApp.directive('ngEnter', [function(){
    console.log("2");
    return {
        link: function($scope, iElm, iAttrs, controller) {
            console.log("3");
        }
    };
}]);

Update(OP made above changes)

The above directive should work

Working Plunkr

Comments