I am new in Angular and I am studying controllers. In my code I setup a simple controller access but when I tried to run in my browser I encountered a series of error messages that looks like this:
"Error: [ng:areq] Argument 'personController' is not a function, got undefined
In my file I haves something like this:
<h1>CONTROLLER</h1>
<div class="row" ng-app="" ng-controller="personController">
<div class="col-sm-6">
<div class="form-group">
<label class="col-md-3">First Name: </label>
<input type="text" class="form-control" ng-model="firstname" />
</div>
<div class="form-group">
<label class="col-md-3">Last Name: </label>
<input type="text" class="form-control" ng-model="lastname" />
</div>
<div class="form-group">
<p>Full Name: {{ firstname + ', ' + lastname }}
</div>
</div>
</div>
<script type="text/javascript">
function personController($scope) {
$scope.firstname = 'Jerielle';
$scope.lastname = 'Doe';
}
</script>
But when I tried to declare a module it works:
<h1>CONTROLLER</h1>
<div class="row" ng-app="myApp" ng-controller="personController">
<div class="col-sm-6">
<div class="form-group">
<label class="col-md-3">First Name: </label>
<input type="text" class="form-control" ng-model="firstname" />
</div>
<div class="form-group">
<label class="col-md-3">Last Name: </label>
<input type="text" class="form-control" ng-model="lastname" />
</div>
<div class="form-group">
<p>Full Name: {{ firstname + ', ' + lastname }}
</div>
</div>
</div>
<script type="text/javascript">
var myApp = angular.module('myApp',[]);
myApp.controller('personController', function($scope) {
$scope.firstname = 'Jerielle';
$scope.lastname = 'Doe';
});
</script>
I am following the tutorials in w3schools.
My question is can i create a controller w/o creating first the module?
1st one you used is nothing but global function declaration of controller, in which you declare controller as function. To analyse the Angular the function should be treated as controller
we need to use post-fix as Controller
.
The reason it is not working because you are using Angular 1.3 + version where the declaration of global function is disabled by default. Whatever you need to do is just by creating a module using angular.module
and then append the component to it.
For getting you code working you need to enable to setting in angular configuration phase
app.config(['$controllerProvider',
function($controllerProvider) {
$controllerProvider.allowGlobals();
}
]);
NOTE
Though you can enable this global declaration function using above setting to make your 1st code working, I'd not prefer to do this. Use
angular.module
to make your code good as area base.
Here is the similar answer which explains