-1

I'm learning AngularJS and have come across this error while implementing a controller.

Can someone point out what's wrong? (followed this exactly as it's shown in a tutorial unless some of the functions are deprecated?)

I get the following error: Argument 'Ctrl' is not a function, got undefined

HTML

<!DOCTYPE html>
<html ng-app>
<head lang="en">
<meta charset="UTF-8">
<title>AngularJS Controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js">   </script>

</head>
<body>
<div ng-controller="Ctrl">
    <input ng-model="name">
    <input ng-model="age">
    <h1>{{ name }}</h1>
    <h1>{{ age }}</h1>
</div>

<script>
    var Ctrl = function($scope) {
        $scope.name = "Noob";
        $scope.age = "21";
    };
</script>

Kincsem
  • 127
  • 2
  • 11
  • Similar question: http://stackoverflow.com/questions/19408011/angularjs-error-argument-firstctrl-is-not-a-function-got-undefined?rq=1 – zakangelle Jan 14 '15 at 23:44
  • 3
    Do they still support that *"function as controller"* stuff in 1.3? Maybe try using the full `angular.module(...).controller(function($scope) { ... })` thing. Also, you're missing the `$scope` argument – Phil Jan 14 '15 at 23:47
  • 1
    Exactly: the old method of defining controllers as global functions is deprecated, one must opt in to use it ([see controllerProvider.allowGlobals()](https://docs.angularjs.org/api/ng/provider/$controllerProvider)). Do what Phil suggests. – Nikos Paraskevopoulos Jan 14 '15 at 23:52
  • You have to pass $scope to ctrl function – Lautaro Cozzani Jan 14 '15 at 23:55

2 Answers2

6

As I know you need to define controller using module.controller method. For example, name your app as myApp

<html ng-app="myApp">

and the js part will be:

angular.module('myApp', [])
    .controller('Ctrl', ['$scope', function($scope) {
        $scope.name = "Noob";
        $scope.age = "21";
    }]);
Rodion
  • 521
  • 2
  • 10
1

You need to define your app

var myApp = angular.module('myApp',[]);

and pass $scope into your controller

var Ctrl = function($scope) {

Here's a fiddle link with those changes: http://jsfiddle.net/fxk7mtb7/

James Waddington
  • 2,834
  • 2
  • 12
  • 23
  • Perhaps you could elaborate? Because when do those things, it works: http://jsfiddle.net/fxk7mtb7/ – James Waddington Jan 15 '15 at 00:01
  • Have tried your solution and still get the same error, even though it works on JSFiddle. – Kincsem Jan 15 '15 at 00:09
  • I made the same mistake in my JSFiddle and used Angular 1.2. Here it is (broken) in 1.3 - http://jsfiddle.net/fxk7mtb7/1/ – Phil Jan 15 '15 at 00:15
  • 2
    Invalid since [AngularJS 1.3.0-beta.15](https://github.com/angular/angular.js/commit/3f2232b5a181512fac23775b1df4a6ebda67d018). – Blackhole Jan 15 '15 at 00:34