10

Why I can't bind to controller's variable inside second controller?

<div ng-app="ManagerApp">
    <div ng-controller="MainCtrl">
        Main: 
        <div ng-repeat="state in states">
            {{state}}
        </div>
        <div ng-controller="InsideCtrl as inside">
            Inside:
            <div ng-repeat="state in inside.states2">
                {{state}}
            </div>
        </div>
    </div>
</div>

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

angularApp.controller('MainCtrl', ['$scope', function ($scope) {
    $scope.states = ["NY", "CA", "WA"];
}]);

angularApp.controller('InsideCtrl', ['$scope', function ($scope) {
    $scope.states2 = ["NY", "CA", "WA"];
}]);

Example: https://jsfiddle.net/nukRe/135/

Second ng-repeat doesn't work.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Dmitriy Kudinov
  • 1,051
  • 5
  • 23
  • 31

3 Answers3

8

As you are using controllerAs you should be using this keyword in controller

angularApp.controller('InsideCtrl', [ function() {
    var vm = this;
    vm.states2 = ["NY", "CA", "WA"];
}]);

Forked Fiddle

NOTE

Technically you should follow one approach at a time. Don't mix up this two pattern together, Either use controllerAs syntax/ Normal controller declaration as you did for MainCtrl using $scope

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 2
    Should someone stumble across this answer, it is correct, but apparently only starting with Angular 1.2.1. The OP fiddle has Angular 1.1.1 selected, and Pankaj has it set to 1.2.1. Took me 15 minutes of "why is this change not working" to figure that out. – ToddK May 03 '17 at 01:46
0

Remove

as inside

from here:

<div ng-controller="InsideCtrl as inside"> such that:

`<div ng-controller="InsideCtrl">`
karn
  • 80
  • 1
  • 10
-3
<div ng-app="ManagerApp">
    <div ng-controller="MainCtrl">
        Main: 
        <div ng-repeat="state in states">
            {{state}}
        </div>
        <div ng-controller="InsideCtrl">
            Inside:
            <div ng-repeat="state in states2">
                {{state}}
            </div>
        </div>
    </div>
</div>
Glorfindel
  • 21,988
  • 13
  • 81
  • 109