-2

We can use $scope as a namespace in angularJS

    angular.module('myApp',[])
           .controller("myController", function($scope){
            $scope.info = "Hello";
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
    <div ng-controller="myController">
         <input type="text" ng-model="info">
         {{info}}
    </div>
  </body>

or we can use this explicitly in controller and use the controller name as namespace in view like:

    angular.module('myApp',[])
           .controller("myController", function(){
            this.info = "Hello";
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="myController as ctrl">
         <input type="text" ng-model="ctrl.info">
         {{ctrl.info}}
    </div>
</body>

My question is what's the difference and what choose to use?

armnotstrong
  • 8,605
  • 16
  • 65
  • 130

1 Answers1

1

This answer in the link Angularjs "Controller as" or "$scope" gives explanation on the controllerAs vs $scope.

Also, from my own experience, i prefer controllerAs syntax. Because, i usually add dynamic data to an Array of objects.

When using $scope option, the ng-repeat was not able to refresh itself when a new data was pushed into the Array, like $scope.dataArray

When using controllerAs syntax, whenever i push a data into the dataArray object, the ng-repeat adds the new data into view.

This happens mainly because, when using $scope syntax, any change to the array creates a new reference. However, using controllerAs syntax, the array reference is always maintained.

Refer ng-repeat not updating on update of array

Community
  • 1
  • 1
Neerajkumar R
  • 84
  • 1
  • 5
  • Thanks @Neerajkummar, I checked the referred answer. So, we are recommended to use "Controller as" syntax right? Are there other pits I should be aware of when using that syntax other than `$scope` ? Cause I read the [developer guide](https://docs.angularjs.org/guide) it rarely mentioned using the `Controller as` syntax, but most examples chose the `$scope`. – armnotstrong Feb 10 '17 at 09:19
  • @Neerajkummar, searching `Controller a vs scope` give me some good duplicate questions, will dig into those and close this question, thanks for the effort and sorry for the trouble. – armnotstrong Feb 10 '17 at 09:25
  • Happy to help @armnotstrong ! So far i have not seen any issues in using the ControllerAs syntax. While using custom directives, initially i found it difficult, as i was unaware of how to use ControllerAs in custom directives. But there is always stackoverflow to help us. Cheers !!! – Neerajkumar R Feb 10 '17 at 09:31