Pass parent scope value into ng-repeat loop in Angular

This should be an extremely simple question, but all of the workarounds I've found are complex. I'm looping through an array of objects in using ng-repeat in a template as follows:

<div class="row-fluid" ng-repeat="message in messages.current|filter:'draft'"> 
    {{ message.subject }} ... {{ }} ...

Since the ng-repeat creates a new scope, the 'campaign' object from the controller doesn't seem to be accessable. Is there any way (aside from adding the campaign object to every item in my array) of getting that value?

Thanks in advance.



You can access the parent scope by using $parent

<div class="row-fluid" ng-repeat="message in messages.current|filter:'draft'"> 
    {{ message.subject }} ... {{ $ }} ...

This is a way that works that doesn't use $parent. It searches upwards through the nested scopes to find the object you're using, however many scopes it has to go through.

In the scope that contains the list, you can define an object with the list as a property, like this:

$scope.obj = {};
$scope.obj.items = ['item1','item2','item3'];

Then have the ng-repeat look like this:

<div ng-repeat="item in obj.items | filter:'item3' track by $index">
    {{obj.items[ obj.items.indexOf(item) ]}}

(you need to use obj.items[ obj.items.indexOf(item) ] rather than obj.items[ $index ] because $index is the index of the filtered array, not the original)

The reason this works is because while obj doesn't exist in the current scope, as you attempt to access its property, Angular will look above the current scope rather than give you an error (if you just tried {{obj}} it would be undefined, and Angular would be happy with giving you nothing instead of looking through higher scopes). This is a helpful link about nested scopes:

In my case I needed the track by $index, because I had an input with ng-model bound to an item in the array, and whenever the model updated, the input would blur because I think the HTML was being re-rendered. A consequence of using track by $index is that items in the array with identical values will be repeated. If you modify one of those other than the 1st one, weird things will happen. Maybe you can filter for uniqueness to avoid that.

I'm relatively new to AngularJS, so please comment if there is anything big I'm missing. But this works, so I'm using it at least.


Another method might be to pass parent scope as a scope variable to the directive i.e.

    ng-repeat="item in items"></my-directive>

It's a bit messy, but you have more control over what the parent actually is and can pass anything in.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.