3

In my web site I am developing a simple AngularJS functionality - firing alert from a 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>

There result in my browser should be:

8

with an alert firing with a message "Hey", right? And what I get is only this in my browser:

{{5 + 3}}

Any ideas how to fix this?

1
  • 1
    Obviously Angular was not bootstraped correctly. Any errors in your console? Try removing (function() { ? Check your angular script path as well Commented Dec 17, 2014 at 14:23

1 Answer 1

12

You app and controller initialization code was never called, 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 won't call the function. To call it, you need to add () at the end before the ;:

(function() { /*code*/})();
// Here ----------------^

More: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression

Sign up to request clarification or add additional context in comments.

1 Comment

@ Rasalom: I've taken the liberty of editing to show what I meant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.