angularjsangularjs-controller

Question about $controller service in AngularJS documentation tutorial


This code is from https://docs.angularjs.org/tutorial/step_02. I was just wondering why the scope.phones.length property is 3 instead of 0, since scope is an empty object. I am not sure what this line is doing:

var ctrl = $controller('PhoneListController', {$scope: scope});

it looks like its setting the $scope in the controller to the empty scope object.

describe('PhoneListController', function() {

  beforeEach(module('phonecatApp'));

  it('should create a `phones` model with 3 phones', inject(function($controller) {
    var scope = {};
    var ctrl = $controller('PhoneListController', {$scope: scope});

    expect(scope.phones.length).toBe(3);
  }));

});

Solution

  • Here you create controller with predefined scope

    var scope = {};
    var ctrl = $controller('PhoneListController', {$scope: scope});
    

    and when the controller starts it has code like:

    $scope.phones = [...]
    

    So when it executes it put to 'phones' array with 3 items.

    You can try playing with it and put some predefined value to scope:

    var scope = {foo: 'bar', phones: [1,2,3]};
    var ctrl = $controller('PhoneListController', {$scope: scope});
    
    phonecatApp.controller('PhoneListController', function PhoneListController($scope) {
      console.log(foo) // 'bar'
      console.log(phones) // [1,2,3]
    
      $scope.phones = [
       {name: 'Nexus S'}
      ]
    
      console.log(phones) // [{name: 'Nexus S'}] here will be an array what we just defined to this property