Mouli
Mouli

Reputation: 91

Angular JS - Controller Undefined

I am a newbie to the AngularJS World. I have this example to define a controller for AngularJS page. I ended up displaying the raw text in the browser when tried to open the page.

I am trying with downloading the angular.js (lib/angular.js) to local filesystem.

The page is as given below:

<!doctype html>
<html ng-app>
    <head>
        <script src="lib/angular.js"></script>
        <script type="text/javascript">
            function MyController($scope) {
                $scope.clock = new Date();
                var updateClock = function() {
                    $scope.clock = new Date();
                };
                setInterval(function() {
                    $scope.$apply(updateClock);
                }, 1000);
                updateClock();
            };
        </script>
    </head>
    <body>
        <div ng-controller="MyController">
            <h1>Hello {{clock}}!</h1>
        </div>
    </body>
</html>

I ended up getting the result as below:

Hello {{clock}}!

In the browser console, I am getting the error log as follows:

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

What am I missing?

Best Regards, Chandra.

Upvotes: 1

Views: 984

Answers (1)

V31
V31

Reputation: 7666

You need to initiate an angular module and create a controller using the same.

For Example:

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

app.controller('MyController', function($scope) {
      $scope.clock = new Date();
      var updateClock = function() {
                $scope.clock = new Date();
      };
      setInterval(function() {
          $scope.$apply(updateClock);
      }, 1000);
      updateClock();
});

And then you need to specify the app in the html markup with ng-app="myApp"

So your html will be:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <div ng-controller="MyController">
            <h1>Hello {{clock}}!</h1>
        </div>
  </body>

</html>

Working Plunkr

Upvotes: 1

Related Questions