Angularjs "Controller as" or "$scope"

Asked
Active3 hr before
Viewed126 times

6 Answers

angularjsscopecontroller
90%

I've written a few answers to this question in the past, and they all essentially boil down to the same thing. In Angular, you are using $scope, even when you aren't expressly referencing it.,I would definitely recommend Controller As syntax.,Unless you're working with a team used to the $scope syntax, definitely use Controller As.,Ultimately, unless you are trying to spin up a 10 minute demo, you really should be using ControllerAs for any serious Angular work.

I've written a few answers to this question in the past, and they all essentially boil down to the same thing. In Angular, you are using $scope, even when you aren't expressly referencing it.

$scope
load more v
88%

With the new Controller as technique you can now do something like this:,Here's an example of what happens when you nest controllers and use scalar values on the $scope.,Traditionally you're probably used to doing something like this:,It's just that the "as" syntax implicitly creates a namespace on the controller's scope, whereas you must create a namespace manually in the latter example. Don't believe me? Here's the proof :)

Traditionally you're probably used to doing something like this:

<div ng-controller="MainController">
  {{ someObj.someProp }}
</div>
load more v
72%

the ngController directive. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope., Controllers , / Controllers ,the controller of a regular directive, or a component directive.

The following example demonstrates creating a GreetingController, which attaches a greeting property containing the string 'Hola!' to the $scope:

var myApp = angular.module('myApp', []);

myApp.controller('GreetingController', ['$scope', function($scope) {
   $scope.greeting = 'Hola!';
}]);

We attach our controller to the DOM using the ng-controller directive. The greeting property can now be data-bound to the template:

<div ng-controller="GreetingController">
  {{ greeting }}
</div>

The following example uses a Controller to add a method, which doubles a number, to the scope:

var myApp = angular.module('myApp', []);

myApp.controller('DoubleController', ['$scope', function($scope) {
   $scope.double = function(value) {
      return value * 2;
   };
}]);

Once the Controller has been attached to the DOM, the double method can be invoked in an AngularJS expression in the template:

<div ng-controller="DoubleController">
  Two times <input ng-model="num"> equals {{ double(num) }}
</div>
<div ng-controller="SpicyController">
 <button ng-click="chiliSpicy()">Chili</button>
 <button ng-click="jalapenoSpicy()">Jalapeño</button>
 <p>The food is {{spice}} spicy!</p>
</div>
var myApp = angular.module('spicyApp1', []);

myApp.controller('SpicyController', ['$scope', function($scope) {
   $scope.spice = 'very';

   $scope.chiliSpicy = function() {
      $scope.spice = 'chili';
   };

   $scope.jalapenoSpicy = function() {
      $scope.spice = 'jalapeño';
   };
}]);
<div ng-controller="SpicyController">
 <input ng-model="customSpice">
 <button ng-click="spicy('chili')">Chili</button>
 <button ng-click="spicy(customSpice)">Custom spice</button>
 <p>The food is {{spice}} spicy!</p>
</div>
var myApp = angular.module('spicyApp2', []);

myApp.controller('SpicyController', ['$scope', function($scope) {
   $scope.customSpice = 'wasabi';
   $scope.spice = 'very';

   $scope.spicy = function(spice) {
      $scope.spice = spice;
   };
}]);
<div class="spicy">
  <div ng-controller="MainController">
    <p>Good {{timeOfDay}}, {{name}}!</p>

    <div ng-controller="ChildController">
      <p>Good {{timeOfDay}}, {{name}}!</p>

      <div ng-controller="GrandChildController">
        <p>Good {{timeOfDay}}, {{name}}!</p>
      </div>
    </div>
  </div>
</div>
div.spicy div {
   padding: 10 px;
   border: solid 2 px blue;
}
var myApp = angular.module('scopeInheritance', []);
myApp.controller('MainController', ['$scope', function($scope) {
   $scope.timeOfDay = 'morning';
   $scope.name = 'Nikki';
}]);
myApp.controller('ChildController', ['$scope', function($scope) {
   $scope.name = 'Mattie';
}]);
myApp.controller('GrandChildController', ['$scope', function($scope) {
   $scope.timeOfDay = 'evening';
   $scope.name = 'Gingerbread Baby';
}]);

Controller Definition:

var myApp = angular.module('myApp', []);

myApp.controller('MyController', function($scope) {
   $scope.spices = [{
         "name": "pasilla",
         "spiciness": "mild"
      },
      {
         "name": "jalapeno",
         "spiciness": "hot hot hot!"
      },
      {
         "name": "habanero",
         "spiciness": "LAVA HOT!!"
      }
   ];
   $scope.spice = "habanero";
});

Controller Test:

describe('myController function', function() {

   describe('myController', function() {
      var $scope;

      beforeEach(module('myApp'));

      beforeEach(inject(function($rootScope, $controller) {
         $scope = $rootScope.$new();
         $controller('MyController', {
            $scope: $scope
         });
      }));

      it('should create "spices" model with 3 spices', function() {
         expect($scope.spices.length).toBe(3);
      });

      it('should set the default value of spice', function() {
         expect($scope.spice).toBe('habanero');
      });
   });
});

If you need to test a nested Controller you must create the same scope hierarchy in your test that exists in the DOM:

describe('state', function() {
   var mainScope, childScope, grandChildScope;

   beforeEach(module('myApp'));

   beforeEach(inject(function($rootScope, $controller) {
      mainScope = $rootScope.$new();
      $controller('MainController', {
         $scope: mainScope
      });
      childScope = mainScope.$new();
      $controller('ChildController', {
         $scope: childScope
      });
      grandChildScope = childScope.$new();
      $controller('GrandChildController', {
         $scope: grandChildScope
      });
   }));

   it('should have over and selected', function() {
      expect(mainScope.timeOfDay).toBe('morning');
      expect(mainScope.name).toBe('Nikki');
      expect(childScope.timeOfDay).toBe('morning');
      expect(childScope.name).toBe('Mattie');
      expect(grandChildScope.timeOfDay).toBe('evening');
      expect(grandChildScope.name).toBe('Gingerbread Baby');
   });
});
load more v
65%

Because we are using dot notation, it becomes impossible to two-way bind to a primitive.,To use our "Controller as" syntax, first, we declare all of our properties and methods on the this property of our controller:,When using nested scopes, it becomes completely clear where a method or property reference belongs to.,By not using the "Controller as" syntax, we can see things get complicated pretty quickly (imagine this in a very large application):

By not using the "Controller as" syntax, we can see things get complicated pretty quickly (imagine this in a very large application):

<div ng-app="app" ng-controller="SiteController">

  <!-- we are pretty sure we are getting the title from the SiteController -->
  <h1>{{title}}</h1>
    
    <div ng-controller="PersonController">
       
        <!-- is this the title from SiteController or PersonController? 
        is there even a title in both? -->
        <h2>{{title}}</h2>
        
    	<div ng-repeat="person in PersonCtrl.people">
        
        	<span>{{person.name}}</span>
            
      	</div>
    
    </div>

</div>
load more v
75%

Controllers are gateway to exchange data & instructions between model and views. In order to make variables available to your view, they must bind to $scope object. A simple example would be

Controllers are gateway to exchange data & instructions between model and views. In order to make variables available to your view, they must bind to $scope object. A simple example would be

angular.module('myApp', []).controller('myCtrl', function($scope) {
   $scope.message = 'Hello World!';
}); < div ng - app = "myApp"
40%

AngularJS Fundamentals 38 lessons ,Let’s change some execution context using angular.bind():,AngularJS Controllers have recently gone under some changes (version 1.2 to be precise). What this means for scopes, Controllers and Angular development is some very subtle but powerful changes. One of those changes I believe is improved architecture, clearer scoping and smarter Controllers., Everything you need to become an AngularJS expert

// <div></div>
app.controller('MainCtrl', function ($scope) {
  $scope.title = 'Some title';
});
load more v

Other "angularjs-scope" queries related to "Angularjs "Controller as" or "$scope""