0

I am new Angular JS, what i confused is about the scope, I understood what it is and its usage, but i didnot understood why we need it when we have class variables in the scope of the controller.

I mean for example:

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
});

<div ng-app="invoice1" ng-controller="InvoiceController as invoice">
 Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
</div>

Now, same code (i mean variable qty) using the scope object as follows:

angular.module('invoice1', [])
.controller('InvoiceController',['$scope', function() {
  $scope.qty = 1;
}]);    
<div ng-app="invoice1" ng-controller="InvoiceController as invoice">
 Quantity: <input type="number" min="0" ng-model="qty" required >
</div>

If you see from both the above code snippets, we can access the variable "qty" with in the scope of the div tag. So, why cannot we use the class variables directly, why we have to inject special factory service like scope.

I am sure, their might be reason for this as they created separate service for scope. Please let me know.

The duplicate question answers is good, but too complicated. Actually, i got the answer, inheritance of scope and objects works well with the use of the scope object. I mean, for example:

<!doctype html>
<html >
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script>
    angular.module('main', [])
    .controller('ParentController',function() {
        this.qty = 999;
    })
    .controller('ChildController', function () {

    });    
    </script>
  </head>
  <body>
        <div ng-app="main">
          <div ng-controller="ParentController as parent">
              <div ng-controller="ChildController as child">    
                child exp: {{ child.qty }}
              </div>
              <b>Invoice:</b>
              <div>
                Quantity: <input type="number" min="0" ng-model="parent.qty" required >
                exp: {{ parent.qty }}
              </div>
          </div>

        </div>
  </body>
</html>

Now, if you observe, in the child controller their is no variable called as qty, so simply it cannot access the parent controller qty variable. Now, replace this with the scope as follows:

<!doctype html>
<html >
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
  angular.module('main', [])
  .controller('ParentController',function($scope) {
      $scope.qty = 999;
  })
  .controller('ChildController', function ($scope) {

  });    
  </script>
</head>
<body>
      <div ng-app="main">
        <div ng-controller="ParentController as parent">
            <div ng-controller="ChildController as child">    
              child exp: {{ qty }}
            </div>
            <b>Invoice:</b>
            <div>
              Quantity: <input type="number" min="0" ng-model="qty" required >
              exp: {{ qty }}
            </div>
        </div>

      </div>
</body>
</html>

Now, even the child controller does not have qty variable it can inherit from the parent controller and executes the expression "child exp: {{ qty }}" perfectly.

Please any more special usage of the scope? Also, please consider that, i will remove this question or accept my question is answered, if any one feel it as duplicate. As a newbie, i just want the difference with some examples.

user3278897
  • 984
  • 10
  • 23
  • `$scope` is more explicit then `this` when dealing with nested routines. both allow for the injection of needed parts (pure functions), but angular happens to be built around magic-named `arguments` instead of `this` – dandavis Jan 06 '16 at 20:00
  • 1
    look at this post http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers – AlainIb Jan 06 '16 at 20:01
  • 1
    and this one http://stackoverflow.com/questions/16619740/angular-should-i-use-this-or-scope – AlainIb Jan 06 '16 at 20:02

1 Answers1

0

first, you should not use ng-controller if possible.

before using ng-controller write a directive and encapsulate the controller inside the directive

var app = angular.module('app',[]);
app.directive('invoice', Invoice);

function Invoice(){    
   return {
      restrict: 'E',
      template: '<div>' +
                   'Quantity: <input type="number" min="0" ng-model="vm.qty" required >' +
                '</div>',
      controller: function InvoiceController(){
                     var vm = this;
                     this.qty = 1;
                  },
      controllerAs: 'vm',
      scope: {}
   };
}


<invoice></invoice>

or use a unique controller for each particular side/route using angular-ui-router.

  var app = angular.module('app', []);
  app.config(Configuration);

  function Configuration($stateProvider) {
    $stateProvider
        .state('app.invoice', {
            url: '/invoice',
            template: '<div>' +
                         'Quantity: <input type="number" min="0" ng-model="vm.qty" required >' +
                      '</div>',
            controller: function InvoiceController(){
                           var vm = this;
                           vm.qty = 1;
                        },
            controllerAs: 'vm'
        });
  }

I think using this or $scope is just a personal preference but if you use this you should decorate it as var vm = this; to prevent this issues in closures or nested functions.

Lusk116
  • 791
  • 1
  • 6
  • 17
  • 1
    "Should not"? That's a strong statement, care to back it up with some references? – Patrick Jan 06 '16 at 20:17
  • @Lusk116 I am sorry, but i didnot think it is just a personal preference of using the scope service. I am reading more on this. I will post my answer. But i didnot understood, your sentence, " ... ...before using ng-controller write a directive and encapsulate ........each particular side/rout", can you provide an example please. – user3278897 Jan 06 '16 at 20:19
  • @Lusk116 thank you for the example code, i will read about the directives nad ui-route. But can i know, why you are opposing the usage of the ng-controller? Is thier any reason, i mean side effects. – user3278897 Jan 06 '16 at 20:46
  • it's kind of a best practice, you normally would not reuse a controller anywhere else but that is exactly what you could do with `ng-controller`, like using the InvoiceController in more than one div on the same page – Lusk116 Jan 06 '16 at 20:55