2

I'm stumped by the example in this fiddle. I'm setting a controller on the element that has ng-repeat, so that a new controller instance is created for each item. Since ng-repeat creates a new scope for each item, the controller should take over the newly created scope such that for ng-repeat="item in items", item becomes $scope.item on the controller. If I use regular controller convention by injecting $scope, this works fine as shown in the example. However, what I thought to be the analogous syntax for "Controller as" does not work, e.g. if I define ng-controller="FirstCtrl as first", then for ng-repeat="item in items", item is not available as this.item. Why is this?

Zack Gao
  • 568
  • 1
  • 4
  • 14

2 Answers2

3

You can use ng-init to make the scope item available to the controller:

HTML:

<div ng-repeat="item in items"
     ng-controller="ItemController as ctrl"
     ng-init="ctrl.init( item )"> 
     ...
</div>

Controller:

.controller('ItemController,[
    function(){
        this.init = function(item){
            this.item = item;
        }
    }
]) 

Updated fiddle:

http://jsfiddle.net/xvdj07q9/3

Jakob E
  • 4,476
  • 1
  • 18
  • 21
0

You said it yourself :

such that for ng-repeat="item in items", item becomes $scope.item on the controller.

It becomes available on the $scope, not on this. And, as pointed out by Yoshi, $scope is not the same as this. (There's some good resources on that matter on SO)

If you're wondering "why can I still see the numbers then ?", that's because you're accessing items from the parent controller.

Community
  • 1
  • 1
Goodzilla
  • 1,483
  • 11
  • 17