Nalaka526
Nalaka526

Reputation: 11464

Controller constructors in global scope are not working

I've seen this basic AngularJS code in a tutorial video which gives the output as expected. But when I try the same code locally it does not work, it shows {{message}} as the output.

<!DOCTYPE html>
<html lang="en" ng-app>
<head>
    <title></title>
</head>
<body>
    <h1 ng-controller="HelloWorldCtrl">{{message}}</h1>
    <script src="Scripts/angular.min.js"></script>
    <script type="text/javascript">

        function HelloWorldCtrl($scope)
        {
            $scope.message = "First Run...";
        }

    </script>
</body>
</html>

In the console it shows an error,

Argument 'HelloWorldCtrl' is not a function, got undefined

Error: [ng:areq] http://errors.angularjs.org/1.3.0-rc.2/ng/areq?p0=HelloWorldCtrl&p1=not%20a%20function%2C%20got%20undefined

Why this same code behaving differently in different environments? Can someone point out what I'm missing here?

Upvotes: 1

Views: 855

Answers (3)

Marian Ban
Marian Ban

Reputation: 8188

there is something changed in angular1.3.rc2! http://jsbin.com/sumifozawiji/1/edit

i got same error. 1.2.25 works: http://jsbin.com/lanavuvaniva/1/edit

Upvotes: 1

bmleite
bmleite

Reputation: 26880

Since Angular v1.3.0-beta defining controller constructors in the global scope is no longer supported.

Upvotes: 1

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

Angular will run, it will bootstrap automatically (because of the ng-app attribute) and expects to find a controller named HelloWorldCtrl (due to the ng-controller="HelloWorldCtrl"). But this controller is defined after Angular, so it is not there at the moment of execution.

The simplest solution is to change the order of the scripts, i.e. put your code before Angular.

Upvotes: 0

Related Questions