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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,922 times
        
    2
            
            
         
    
    
        Zack Gao
        
- 568
- 1
- 4
- 14
- 
                    I guess because `$scope != this`. – Yoshi Sep 17 '14 at 15:18
2 Answers
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:
 
    
    
        Jakob E
        
- 4,476
- 1
- 18
- 21
0
            You said it yourself :
such that for
ng-repeat="item in items",itembecomes$scope.itemon 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.
 
    