Joy Ram Sen Gupta Joy Ram Sen Gupta - 2 months ago 160
AngularJS Question

Angular JS 1.5.X shows errors with controller

I am writing a simple controller example with angular.js version 1.5.X which has some issues worth noting. The problem is only encountered with Angular JS version 1.5.X but I have tested the code with Angular JS V 1.2.X which works as expected. I am not sure if I am doing something in an outdated fashion ? I am unable to understand the console logs.

My Code-

<!doctype html>
<html lang="en" ng-app="">
<head>
<meta charset="UTF-8">
<title>Angular Demo</title>
<script src="lib/angular/angular.min.1.5.X.js"></script>
</head>
<body>

<div ng-controller = "MyController">
<h1>{{author.name}}</h1>
<p>{{ author.title + ', ' + author.company }}</p>
</div>

<script>
function MyController($scope) {
$scope.author = {
'name' : 'Ray Villalobos',
'title' : 'Staff Author',
'company' : 'Lynda.com'
}
}
</script>
</body>
</html>


Result:

{{author.name}}

{{ author.title + ', ' + author.company }}

Console Log:

angular.min.1.5.X.js:118 Error: [ng:areq] http://errors.angularjs.org/1.5.8/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:6:412
at sb (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:23:18)
at Pa (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:23:105)
at file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:89:310
at ag (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:72:419)
at p (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:64:262)
at g (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:58:481)
at g (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:58:498)
at g (file:///G:/Programming-Joy/Web/JavaScript/JavaScript%20Essential%20Training%20Lynda/AngularJs/lib/angular/angular.min.1.5.X.js:58:498)

Answer

With Angular above 1.3 you need to defined controller like this,

 app.controller("MyController" , function($scope)
   {
       $scope.author = {
      'name' : 'Ray Villalobos',
      'title' : 'Staff Author',
      'company' : 'Lynda.com'
      }
   }); 

DEMO APP

Comments