I'm new to Angular and I'm going through the Intro to Angular videos from the Angular site. My code isn't working and I have no idea why not. I get the error
Error: ng:areq
Bad Argument
Argument 'MainController' is not a function, got undefined
Here's my code.
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Angular Demo</title>
</head>
<body>
<main ng-controller="MainController">
<p>{{message}}</p>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
function MainController($scope) {
$scope.message = "Controller Example";
}
</script>
</body>
</html>
What am I doing wrong?
AngularJS ControllersAngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
As pointed in previous comments, angular2 doesn't works like angularjs (or angular1) there is no controller in this version, but I think you can implement an equivalent app just using components.
After angular version 1.3 global controller function declaration is disabled
You need to use modularise approach in order to make it work.
You should define angular.module first and then include angular components to it
Demo
angular.module('app', [])
.controller('MainController', function ($scope) {
$scope.message = "Controller Example";
})
Then change ng-app
to use that module ng-app="app"
Just defining the function will not be a controller. You need to use like this:
var app = angular.module('myApp',[]);
app.controller('MainController',MainController);
function MainController($scope) {
$scope.message = "Controller Example";
}
And ensure to use myApp in your html like this:
<html lang="en" ng-app="myApp">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With