Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js Controller Not Working

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?

like image 293
Halcyon Avatar asked Sep 10 '15 04:09

Halcyon


People also ask

Can you create controller in AngularJS?

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.

What is an AngularJS controller?

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.

Does angular 2 have controllers?

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.


2 Answers

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"

like image 103
Pankaj Parkar Avatar answered Sep 18 '22 18:09

Pankaj Parkar


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">
like image 43
Bhojendra Rauniyar Avatar answered Sep 17 '22 18:09

Bhojendra Rauniyar