1
votes

I am new to angular.js. I am getting the following error while executing a simple controller example.

Error: [ng:areq] http://errors.angularjs.org/1.4.7/ng/areq?p0=Mycontroller&p1=not%20a%20function%2C%20got%20undefined at Error (native)

index.html:

<!DOCTYPE html>
<html ng-app>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

  <script src="script.js"></script>
</head>

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

</html>

script.js

var Mycontroller = function($scope){
  $scope.message = "Hello Angular";
};

Output:

{{message}}

Where am i going wrong?

2
with last version you should create module and add controller to itGrundy
Check this site: learn-angular.orgFernando Pinheiro
you code work for angular version before 1.3.0Grundy
Global function declaration are not allowed in angular 1.3+ versions.Vineet

2 Answers

3
votes

You should create a module, and then attach a controller to it. This is the angular way. Your code should look like this.

<html ng-app="my-app">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

  <script src="script.js"></script>
</head>

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

</html>

In your JavaScript file, you should have this

angular.module('my-app', [])
    .controller('Mycontroller', function($scope) {
         $scope.message = "Hello Angular";
    });

Plunker: http://plnkr.co/edit/tYIQOlNALzco9zobAIO0?p=preview

0
votes

try this it works

HTML page

 <!doctype html>
 <html ng-app="MyApp">
    <head>
    <title>HTML page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="hello.js"></script>
  </head>

<body>
    <div ng-controller="Hello">

        <p>The ID is {{greeting.id}}</p>
        <p>The content is {{greeting.content}}</p>
        <p>{{message}}</p>
    </div>
</body>

hello.js

      var app = angular.module("MyApp", []);
     app.controller("Hello", function($scope, $http){Helloz($scope, $http);});
     function Helloz($scope, $http) {
     //$http.get('http://rest-service.guides.spring.io/greeting').
     $http.get('/person').
       then(function(data) {
         $scope.greeting =angular.fromJson(data).data;
         $scope.message=angular.fromJson(data).data;
     },null);
 }