narahari_arjun
narahari_arjun

Reputation: 643

what is the difference between these two ways of using controllers in AngularJs?

I have started angularjs very recently and i have found these two ways of using controllers.

This one does not give me any output

<html ng-app="">
<body>
<div>
    Name : <input type="text" ng-model="name">
    {{name}}
</div><br>
    <div ng-controller="SimpleController">
    <ul>
        <li ng-repeat="cust in customers">
            {{cust.city}}
        </li>
    </ul>
</div><br>
<script src = "D://angularJs/angular.min.js"></script>

<script>
function SimpleController($scope){
    $scope.customers = [
    {names:'Arjun Narahari',city:'Mumbai'},
    {names:'Santosh Rangarajan',city:'Pune'},
    ];
}
</script>

This one gives me proper output

<html ng-app="myApp">
<body>
<div ng-controller="SimpleController">
    <ul>
        <li ng-repeat="cust in customers">
            {{cust.city}}
        </li>
    </ul>
</div><br>
<script src = "D://angularJs/angular.min.js"></script>

<script>
angular.module("myApp",[]).controller("SimpleController",function($scope){
    $scope.customers = [
    {names:'Arjun Narahari',city:'Mumbai'},
    {names:'Santosh Rangarajan',city:'Pune'},
    ];
});
</script>

Output

Mumbai Pune

Can anyone explain me why the first way does not work ? Thank you

Upvotes: 0

Views: 39

Answers (2)

mcfedr
mcfedr

Reputation: 7975

The first version, using a global function, was the most basic example for a long time with Angular, but as of version 1.3 it has been disabled.

Now the only way to define a controller is as in your second example.

Basically the first way was only ever used for basic tutorials. Apps of any size generally don't want to be filling up the global scope and design for better modularity. So as much as the second option feels like you are doing more for no reason at the moment, you will appreciate it as your app grows!

Upvotes: 1

Simon H
Simon H

Reputation: 21005

As you can see, the second has this extra code

angular.module("myApp",[]).

which actually sets up Angular. Without it, function simpleController() is sitting there with nothing using it

Upvotes: 1

Related Questions