Pass parent scope value into ng-repeat loop in Angular

放肆的年华 提交于 2019-11-27 18:19:04

You can access the parent scope by using $parent

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

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) ]}}
</div>

(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: http://www.angularjshub.com/examples/basics/nestedcontrollers/

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.

<my-directive 
    md-parent-scope="this" 
    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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!