Most simple AngularJS code not working
On my website, I am developing a simple AngularJS function - fired warning from module controller. This is my code:
app1.js:
(function() {
var app1 = angular.module('myApp', []);
app1.controller('MyController', function() {
alert('Hey');
});
});
Index.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head>
<title>Angular</title>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app1.js"></script>
</head>
<body ng-controller="MyController">
{{5 + 3}}
</body>
</html>
As a result, my browser should be:
-
with a firing warning with the message "Hey", right? And what I get is this in my browser only:
{{5 + 3}}
Any ideas how to fix this?
+3
source to share
1 answer
You haven't called the application and controller initialization code, you need to do this:
(function() {
var app1 = angular.module('myApp', []);
app1.controller('MyController', function() {
alert('Hey');
});
})(); // <=== Change is here
Explanation:
(function() { /*code*/});
will create an anonymous function, but will not call the function. To call it, you need to add ()
to the end before ;
:
(function() { /*code*/})();
// Here ----------------^
More details: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
+12
source to share