AngularJS beginner: ng controller not working

I'm just trying to figure out the basics of AngularJS. I tried writing a simple MVC application, but the controller does not seem to work. The file can find angular lib just to find, I already tested this by excluding "ng-controller".

<!DOCTYPE html> <html ng-app> <head> <script src='js/lib/angular.js'></script> <script> // controller function MyFirstCtrl($scope) { // model var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant']; $scope.ourEmployees = employees; } </script> </head> <body ng-controller='MyFirstCtrl'> <!-- view --> <h2>Number of employees: {{ourEmployees.length}}</h2> </body> </html> 

EDIT: The error log states the following:

 Uncaught SyntaxError: Unexpected token ILLEGAL , line 9 Uncaught SyntaxError: Unexpected token { , line 19 Error: [ng:areq] Argument 'MyFirstCtrl' is not a function, got undefined 

EDIT2: I changed the code to this:

 <!DOCTYPE html> <html ng-app='MVCExample'> <head> <script src='js/lib/angular.js'></script> <script> var app = angular.module('MVCExample', []); // controller app.controller("MyFirstCtrl", function($scope) { // model var employees = ['Christopher Grant', 'Monica Grant', 'Christopher Grant', 'Jennifer Grant']; $scope.ourEmployees = employees; }); </script> </head> <body ng-controller='MyFirstCtrl'> <!-- view --> <h2>Number of employees: {{ourEmployees.length}}</h2> </body> </html> 

It also turned out that the "employees" array that I had was illegal, because I had one row entry divided into two rows. The above work. The initial book I use must be out of date, which is unsuccessful.

+6
source share
3 answers

If you are using angularjs version 1.3+, you cannot declare a global controller as shown above.

You must initialize as shown below.

 <div ng-app="appname" ng-controller="MyFirstCtrl"> var app = angular.module('appname', []); app.controller('MyFirstCtrl',function(){ //controller code here }); 
+10
source

I don’t see how you initialize the angularjs application, don’t know if this is included in the js file you linked, but basically you should have something like this:

 var app = angular.module("appName", []).controller("ControllerName", function ($scope){ //your controller code here }); 

And then in your HTML code something like:

 <html ng-app="appName"> 
+2
source

Add a controller to the angular module

 .module('LogIn') .controller('LoginController', LoginController) 

image

-1
source

All Articles