Reputation: 61
Im trying to follow along a tutorial but this code doesn't work for me. Can someone expain why and how to solve it? I think its to do with ng-controller but not sure why.
<!doctype html>
<html ng-app>
<head>
<title>AngularJS 2</title>
<script src="angular.min.js"></script>
</head>
<body ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{ author.title + ', ' + author.company }}</p>
<script>
function MyController($scope) {
$scope.author = {
'name' : 'Ray Villa',
'title' : 'Staff Author',
'company' : 'boss`enter code here`.com'
}
}
</script>
</body>
</html>
Upvotes: 1
Views: 231
Reputation: 28289
Your code would not work with angular 1.3+ because your are defining the controller as a global function.
From AngularJS documentation :
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 Define the controller as follows instead :
<html ng-app="myApp">
<head>
<title>AngularJS 2</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{ author.title + ', ' + author.company }}</p>
<script>
angular.module('myApp', []);
angular.module('myApp').controller('MyController', function ($scope) {
$scope.author = {
'name': 'Ray Villa',
'title': 'Staff Author',
'company': 'boss`enter code here`.com'
}
});
</script>
</body>
</html>
Upvotes: 2
Reputation: 4457
You are missing the Angular context.
Your application requires a module, so you need to write ng-app="myApp"
and use that module to register your controller function.
function MyController($scope) { /* ... */ }
angular.module('myApp, []).controller('MyController', MyController);
This will tell Angular to bootstrap your (myApp) application and register that specific controller.
Upvotes: 0