user2730490
user2730490

Reputation: 297

Understanding Angularjs scope

I am working angularjs scope, I countered an interesting problem. I have the following html structure:

<body ng-app='myApp'>
      <div ng-controller='myCtrl'> 
        <select ng-model='selectedOption'
                ng-options='option.size for option in options'
                ng-change='update(selectedOption)'></select>
      </div>

      <div ng-controller='myCtrl'>
        <ul>
          <li ng-repeat='asset in assets'>
            {{asset}}
          </li>
        </ul>
      </div>
   </body>

Notice that i have 2 controllers that have the same name 'myCtrl'.

And the following is my javascript code:

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

myApp.factory('Assets', function() {
  return {
    assets: [{test:1}]
  };
});

myApp.controller('myCtrl', function($scope, Assets, $rootScope) {

  $scope.assets = Assets.assets;

  var temp = [
    {test:5},
    {test:6},
    {test:7}
  ];

  $scope.options = [
    {size: 1},
    {size: 2},
    {size: 3},
    {size: 4}
  ];
  $scope.selectedOption = $scope.options[0];

  $scope.update = function(value) {

    console.log($scope.$id);

    /*for(var i = 1; i < value.size; i=i+value.size) {
      $scope.assets.push({
        test: value.size
      });
    }*/

    $scope.assets = temp;
  };

});

When I run the code and select a option from the dropdown list, console will log '003' which is the first controller's $id. Why inside the 'update' function I can't get the second controller's scope? Is there a way to get it?

Here is a link to JSbin: http://jsbin.com/gecizuwaku/2/edit?html,js,console,output

Upvotes: 2

Views: 130

Answers (1)

GregL
GregL

Reputation: 38103

You could, but you would need to invoke the update() function inside the second ng-controller="myCtrl" block.

The way ng-controller roughly works is that it creates a child scope of the scope of the element it is on. Then it instantiates the controller function, resolving any dependencies and passing them in, along with this new child scope as $scope. That means each ng-controller instance will create a new instance of the controller function with a new child scope supplied.

In your specific case, the two scopes created by ng-controller will be siblings.

You could see the second scope's $id by running the following in the developer console:

angular.element('ul').scope().$id

Or by invoking the update() method:

angular.element('ul').scope().update()

which would log the $id to the console. It will likely be the next sequential id, which in your case will be "004".

Upvotes: 3

Related Questions