Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The controller with the name 'mainController' is not registered

i have this code in my script.js file

var mainController = function($scope){
  $scope.message = "Plunker";
};

and this is my HTML

<!DOCTYPE html>
<html ng-app>
    <head>
        <script data-require="[email protected]" data-semver="1.6.1"    src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
    </head>

    <body ng-controller="mainController">
        <h1>Hello {{ message }}</h1>
    </body>
</html>

i declared ng-app in the opening html tag

but i get this error on my console that mainController is not registered

like image 977
engr_ejo Avatar asked Feb 07 '17 08:02

engr_ejo


2 Answers

The code is following an obsolete example.

Migrating from 1.2 to 1.3

Controllers Due to 3f2232b5, $controller will no longer look for controllers on window. The old behavior of looking on window for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default.

To migrate, register your controllers with modules rather than exposing them as globals:

Before:

function MyController() {
  // ...
}

After:

angular.module('myApp', []).controller('MyController', [function() {
  // ...
}]);

-- AngularJS Developer Guide -- Migrating from 1.2 to 1.3

like image 174
georgeawg Avatar answered Oct 21 '22 09:10

georgeawg


To paraphrase http://www.w3schools.com/angular/angular_modules.asp

 <div ng-app="myApp" ng-controller="mainController">
{{ firstName + " " + lastName }}
</div>

<script>

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

app.controller("mainController", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});

</script> 

The important line is

    app.controller("mainController", function($scope) 

which injects your controller into your app

like image 41
Mawg says reinstate Monica Avatar answered Oct 21 '22 07:10

Mawg says reinstate Monica