Issue
The following Angular js code throws the error-
"angular.js:13550 TypeError: Cannot read property 'compile' of undefined" for the code-
HelloWorld.html
<!DOCTYPE html>
<html ng-app="module1">
<head>
<title>My First Custom Directive</title>
<script src="../angular.js"></script>
<script src="helloworldDirective.js"></script>
</head>
<body>
<hello-world></hello-world>
</body>
</html>
helloWorldDirective.js-
(function() {
var module1=angular.module('module1',[]);
module1.directive('helloWorld',function(){
return
{
template:'Hello Somesh!!Keep it up.'
};
});
}());
But when I replace the Javascript file with the following code it works:
(function() {
var module1=angular.module('module1',[]);
var helloWorld=function()
{
var directive={};
directive.template='Hello Somesh!!Keep it up.';
return directive;
}
module1.directive('helloWorld',helloWorld);
}());
Both codes are doing basically the same thing but one is failing. Any thoughts?
Solution
JavaScript's Automatic Semicolon Injection turns this:
return
{
template:'Hello Somesh!!Keep it up.'
};
into this:
return;
{
template:'Hello Somesh!!Keep it up.'
};
a return, followed by a useless code block. (The template:
is treated as a label.)
Debugging hint: JSHint or JSLint would have found this error for you.
Style hint: In JavaScript, always keep open braces on the same line... though only the return
and throw
statement are affect by this particular issue.
Answered By - Jeremy J Starcher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.