Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The simpliest AngularJS code not working

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?

like image 741
kiriz Avatar asked Jun 02 '26 21:06

kiriz


1 Answers

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

like image 99
Rasalom Avatar answered Jun 04 '26 09:06

Rasalom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!