简体   繁体   中英

What are different way of writing controller in AngularJS?

1- Are there multiple ways of writing controllers using same version of AngularJS? 2- Is controller declaration is different for different versions of Angular?"

I have seen two ways of declaring controller so far. I do not know which one is better and why.

1-

myAppName.controller('categoryCtrl', function ($scope, categoryData) {
    $scope.menu = categoryData.all;
    $scope.menuTypes = {'Spotlight': false, 'All': true};

});

2

function myCtrl($scope) {
  $scope.master = {};

  $scope.update = function(user) {
    $scope.master = angular.copy(user);
  };

  $scope.reset = function() {
    $scope.user = angular.copy($scope.master);
  };
}

looking for explanation.

[ 1 ]

Lets say we have controller myCtrl :

function myCtrl($scope) {
  $scope.boo = 'boo';
}

So to print $scope.boo value we can write:

<div ng-controller = "myCtrl">
    <pre>{{boo}}</pre>
</div>

[ 2 ]

However I can initiate controller like:

 function myCtrl($scope) {
  $scope.boo = 'boo';
 }

app.controller('booCntrl',myCtrl);

And print value in HTML:

<div ng-controller = "booCntrl">
    <pre>{{boo}}</pre>
</div>

Get the same result. Because I use myCtrl method and put it as argument into app.controller

[ 3 ]

Third option:

app.controller('fessCntrl', function ($scope) {
     $scope.boo = 'boo';
});
app.$inject = ['$scope'];

and print:

<div ng-controller = "fessCntrl"> 
 <pre>fessCntrl: {{boo}}</pre>
</div>

As I know 1st option is good when you try to use dynamic controllers like in followed example: See Demo Fiddle . 3d option doesn't work here, we can't load controller by name from app.controller .

But I prefer 3d option in case of "root" controller just for code clearness. (1-2 options seem like simple methods).

hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM