adapt-dev
adapt-dev

Reputation: 1768

How to pass an item from ng-repeat to a controller created/loaded by ng-include?

I have an ng-repeat that loads an ng-include. I'd like to have a separate controller inside the view that the ng-include loads.

But I'm having trouble accessing the item from ng-repeat in that controller. I tried something like this, and it fails.

How do I get at result inside of SubController?

    <div ng-repeat="result in results">
            <div class="box" ng-include="view/someinclude.html"></div>
    </div>

view/someinclude.html:

<div ng-controller="SubController">
     ...
</div>

controller js:

angular.module('SubController', [])
    .controller('SubController', ['$scope',
        function ($scope) {
            //fails
            console.log($scope.result);
        }
    ]);

Upvotes: 0

Views: 279

Answers (3)

Abdul23
Abdul23

Reputation: 6005

Try using $parent.result instead of $scope.result inside your controller as ng-include creates a new scope of its own that prototypically inherits from its parent scope.

Upvotes: 1

BrightEyed
BrightEyed

Reputation: 386

Make sure your scopes are a part of the same module, or they they're different include one in the other, if that's not the problem then it'll be something outside what you've shown, as something like this:

angular.module("app").controller.(testController", ["$scope", function($scope){
     console.log($scope.x)
}])

with:

<div ng-repeat = "x in [1,2]">
        <div ng-include = "'./views/vew.test.html'">
        </div>
</div>

and in vew.test.html:

<div ng-controller = "testController">
    {{x}}
</div>

Will wack 1 and 2 on the screen and in the console.

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52837

Make sure you're using the same module:

angular.module('SubController').controller('SubController', function() {...});

Upvotes: 1

Related Questions