Reputation: 28338
I've got a weird pipe problem which I haven't found an explanation to when searching through the pipe docs.
Basically I have a pipe which sorts an array of objects, problem is that if more lists are being repeated from the same source, then those lists will also change which is odd. It seems like the pipe is modifying the original source which then causes everything based on it to change.
If I repeat from this:
public options: any[] = [
{label: 'Item 1'},
{label: 'Item 3'},
{label: 'Item 6'},
{label: 'Item 2'}
];
Then have a list which can be filtered out by a query:
<div>
<form-input [(model)]="query" placeholder="Write a search query"></form-input>
<ul>
<li *ngFor="#option of options | filterObjects:query">
{{option.label}}
</li>
</ul>
</div>
And then have another one where I use a pipe that sorts:
<!-- This list's pipe will also affect the list above since they repeat from the same list -->
<div>
<ul>
<li *ngFor="#option of options | orderByProperty:'label'">
{{option.label}}
</li>
</ul>
</div>
Pipe that sorts:
import {Pipe} from 'angular2/core';
@Pipe({
name: 'orderByProperty'
})
export class OrderByPropertyPipe {
transform(value, args) {
if (!args[0]) {
return value;
}
else if (value) {
return value.sort(function(a,b) {
return (a[args[0]] > b[args[0]]) ? 1 : ((b[args[0]] > a[args[0]]) ? -1 : 0);
});
}
}
}
I will get both lists showing:
How can I avoid this rather odd behaviour?
Upvotes: 1
Views: 1408
Reputation: 202256
The sort
method updates the current array and return it. Not to update the original array, you need to create a new one, for example using the slice
method.
You could try the following:
@Pipe({
name: 'orderByProperty'
})
export class OrderByPropertyPipe {
transform(value, args) {
var sortedArray = value.slice();
if (!args[0]) {
return sortedArray;
} else if (sortedArray) {
return sortedArray.sort(function(a,b) {
return (a[args[0]] > b[args[0]]) ? 1 :
((b[args[0]] > a[args[0]]) ? -1 : 0);
});
}
}
}
Upvotes: 2