A controller named "mainController" is not registered

I have this code in a script.js file

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

and this is my HTML

<!DOCTYPE html>
<html ng-app>
    <head>
        <script data-require="angular.js@1.6.1" 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

+4
source share
4 answers

Rephrase 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> 

Important line

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

which injects your controller into your application

+2
source

The code follows an obsolete example.

Migration from 1.2 to 1.3

- 3f2232b5, $controller . , . , , .

, , :

:

function MyController() {
  // ...
}

:

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

- AngularJS - 1.2 1.3

+3

.

app.js

 var myApp = angular.module('app', []);
 myApp.controller('mainController', function($scope){
    $scope.message = "Plunker";     
 });

html

<!DOCTYPE html>
<html ng-app="app">
    <head>
        <script data-require="angular.js@1.6.1" 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>
+1

, script.js

var app = angular.module('myApp', []);
 app.controller('mainController', function($scope) {
  $scope.message= "msg";

   });
0

Source: https://habr.com/ru/post/1669020/


All Articles