Hans
Hans

Reputation: 165

AngularJS Beginner is not a function, got undefined

<html>
    <head>
    <script type="text/javascript" src="resources/js/angular.js"></script>
    <script type="text/javascript" src="resources/js/app.js"></script>
    </head>
    <body ng-app>

    <div ng-controller="DatumCtrl">
        <p>{{datum}}</p>
    </div>
    </body>
    </html>

app.js:

var DatumCtrl = function($scope) {
    $scope.datum = new Date();
};

With this I get an error:

"Error: [ng:areq] Argument 'DatumCtrl' is not a function, got undefined.

I have copied tis code from an introductory articel on AngularJS and have no prior experience with AngularJS.

Upvotes: 0

Views: 128

Answers (2)

Anatoly Ruchka
Anatoly Ruchka

Reputation: 543

This code example goes from Controller Basics Tutorial by Scot Allen and it will throw exception like

"Error: [ng:areq] Argument 'MainController' is not a function, got undefined

So the reason of this that since v1.3 you can't have global controllers

index.html

<!DOCTYPE html>
<html ng-app>

<head>
  <script data-require="[email protected]" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
  <title>{{ 55 * 2}}</title>
</head>

<body ng-controller="MainController">
  <h1> {{message}}</h1>
</body>

</html>

script.js before v1.3

var MainController = function($scope){
  $scope.message = "Hello I am Angular";
};

script.js after v1.3

angular.module('controllerExample', [])
  .controller('MainController', ['$scope', MainController]);

function MainController($scope){
  $scope.message = "Hello I am Angular";
}

and in your index.html

<html ng-app="controllerExample">

see Plunker with solved example

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

To have the controller you need to have the module first:

var app = angular.module('MyApp',[]);

And use : ng-app="MyApp"

Upvotes: 2

Related Questions