0

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);
  }));

});
4
  • $controller is a service which calls a controller. in this case it calls PhoneListController. In this tutorial, at that point there is a $scope.phones array with 3 elements inside PhoneListController. Commented Aug 1, 2019 at 3:52
  • what does this do? {$scope: scope} Commented Aug 1, 2019 at 3:54
  • inject $scope dependency inside controller. it you see PhoneListController, it has $scope as a dependency Commented Aug 1, 2019 at 3:55
  • I just saw this in the tutorial: a controller is simply a constructor function that takes a $scope parameter. In this case, scope is the argument, and then scope.phones = [phone1, phone2, phone3] is done inside the controller right? Anyway, you can post it as an answer and I'll accept it. Commented Aug 1, 2019 at 4:05

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.