user275157
user275157

Reputation: 1352

AngularJS directives erroring out - Cannot read property 'compile' of undefined

Newbie to AngularJS and trying to create a simple directive. The code fails with a TypeError: Cannot read property 'compile' of undefined. Any suggestions would be greatly appreciated.

JS

var xx = angular.module('myApp', []);
xx.directive('myFoo', 
             function(){
                 return 
                 {
                     template:'23'
                 };                     
});

HTML

<div ng-app="myApp">
<div my-foo></div>
</div>

You can find the code and error here https://jsfiddle.net/p11qqrxx/15/

Upvotes: 12

Views: 17118

Answers (4)

ravinder
ravinder

Reputation: 1

xx.directive('myFoo',

function () { var obje={ restrict: 'A', //defaults its A no need of it to declare. template: '23' return obje; } });

Upvotes: 0

Shivprasad Koirala
Shivprasad Koirala

Reputation: 28646

This is not a issue of Angular but its the way javascript return syntaxes are written and executed. I have created a simple video which demonstrates this issue in more detail. You can see this video from this link.

https://www.facebook.com/shivprasad.koirala/videos/910570055693818/

Now for the long answer. In javascript "return" and "return ;" are one the same and "{}" is a anonymous function.

When you write return and "{" in the next line its two statements one return and the "{}" is a anonymous function.Program returns from the "return" syntax and the code inside the curly bracket is never executed or we can say its a unreachable code.So it returns back "undefined".

return  // returns from this step itself
{
  // any code here will never execute
 // unreachable code
}

When you write the curly bracket just after return statment it treats them as one block of code and also executes the code inside the curly bracket.

return{
// any code here will execute
}

So its all about where your curly bracket is after the return statement.

Upvotes: 2

Dylan Watt
Dylan Watt

Reputation: 3387

It's just your return statement.

Bad:

return 
{} // This returns undefined, return is odd and doesn't look at the next line

Good:

return{
} // Returns an empty object, always open your object on the same line as the return

Better:

var directive = {};
return directive; // How I always do it, to avoid the issue.

Upvotes: 36

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You also referred AngularJs 1.0.0 which was too old, I updated it to 1.1

Change directive to this

xx.directive('myFoo',

function () {
    return {
        restrict: 'A', //defaults its A no need of it to declare.
        template: '23'
    };
});

Working Fiddle

Upvotes: 0

Related Questions