0

Why doesn't this code work? I am trying to find it during last four days...

Error: [ng:areq] Argument 'mainCtrl' is not a function, got undefined

HTML:

<!doctype html>
  <html ng-app>
    <head>
    <title> test angular html </title>
    <script src="bower_components/angular/angular.js"> </script>
    <script>
    function mainCtrl($scope) {
        $scope.value = 100;
    } 
    </script>
  </head>

  <body ng-controller="mainCtrl">
    <h1> {{value}} </h1>
  </body>
</html>
floribon
  • 19,175
  • 5
  • 54
  • 66
  • which version ofangular do you use? you may need to declare you module (`angular.module(name, [])`) with the recent ones. – floribon Mar 07 '15 at 01:47
  • I am using 1.3.14. below also didn't work. angular.module("myapp", [])) { function mainCtrl($scope) { $scope.value = 100; } } – Sungchan Lee Mar 07 '15 at 01:54
  • you have to give you app a name with the ng-app and then in your javascript add angular.module('yourappname', []) – massintha Mar 07 '15 at 01:55
  • possible duplicate of [Controller not a function, got undefined, while defining controllers globally](http://stackoverflow.com/questions/25111831/controller-not-a-function-got-undefined-while-defining-controllers-globally) – PSL Mar 07 '15 at 01:56
  • below is working.. thanks floribon! Is it mandatory to put them in module in the latest version??? test angular html

    {{value}}

    – Sungchan Lee Mar 07 '15 at 02:02

1 Answers1

2

When you are using a framework like angular you must declare some logic to work (angular 1.3+), for example.

You must create the main module of your app:

angular.module('yourmodule', [])  // the last parameter [] create the module, that array are the dependencies

With your module created you must attach the controller to the module, you have a function mainCtrl created, i'm gonna use it:

var module = angular.module('yourmodule')  // without the second argument, get the module with that name
module.controller('mainCtrl', mainCtrl) // This assign the name mainCtrl the function mainCtrl

And finally, add to ng-app the module created:

  <html ng-app="yourmodule">

I hope this work, and welcome to angular world!!!

Jesús Quintana
  • 1,803
  • 13
  • 18
  • Really? I did not know. Thank you!!! (I edit the answer). But well anyone want start a project with an old version on angular 1.2, and most if the next week come the 1.4 version – Jesús Quintana Mar 07 '15 at 02:26
  • But the current 1.3 is a stable one, and the writer of the question maybe don't have a production solution with the angular 1.2 (Maybe is learning the framework). And in the ng-conf mention not big break issue between 1.3 and 1.4. So start with the angular 1.3 is not a bad idea for later migrating to 1.4 – Jesús Quintana Mar 07 '15 at 02:32