3

I am beginner of Angular 1, I understood that $scope is glue between vew and modal.

Could anyone tell me the difference between these three ways of defining a controller.

1)

   (function(angular) {
      'use strict';
       var myApp = angular.module('myApp', []);
       myApp.controller('namesCtrl', ['$scope', function($scope) {
         $scope.customSpice = 'wasabi';

       }]);
    })(window.angular);

Is there any use of passing array with values ['$scope',function]. Is function alone is not sufficient?

2)

angular.module('myApp', []).controller('namesCtrl', function($scope) {

});

3)

  (function(angular) {
    'use strict';
     angular.module('invoice1', [])
     .controller('namesCtrl', function namesCtrl() {
        this.customSpice = 'wasabi';
      });
    })(window.angular);

How they bond data to $scope in 3rd example I found this example at https://docs.angularjs.org/guide/concepts.

Joshna Gunturu
  • 161
  • 1
  • 2
  • 13

2 Answers2

2

Case 3rd:

Controlled is used as "controller as" syntax. This is the latest practice of binding with the DOM. Here the $scope variable is use in the context of current controller inside HTML.

However to use it inside closures or other functions you need to make a copy of reference to this context

eg: var cs = this;

Case 1 and 2 are almost same except that $scope is passed as dependency in case 1.

Read more here for benefits of each Angular: Should I use this or $scope

Community
  • 1
  • 1
Rishabh
  • 1,205
  • 1
  • 11
  • 20
1
  1. ['$scope', function($scope){}] is called as Inline Array Annotation. Angular maps $scope(after minification say a) with '$scope'. Useful when you plan to minify your code.
  2. Implicit Annotation. Be careful in case of minification.
  3. controllerAs. When you are using controllerAs syntax, e.g. "myCtrl as ct" angular does $scope.ct = this. Here, also you are using $scope as glue between view and modal.
ram1993
  • 979
  • 1
  • 9
  • 13