Michele Boscagin Michele Boscagin - 2 months ago 22
AngularJS Question

Custom filter angular on ng-repeat for stike text if disabled

I'd like to add a custom filter on my angularJS app. I want di strike text like this way if the object in the ng-repat has the isDeleted flag set as true.
Code: here the HTML:

<table id="tableText" class="table table-hover table-striped" ng-init="allNews()">
<tr>
<th>Titolo</th>
<th>Text</th>
<th>Disattivato</th>
<th>Modifica</th>
<th ng-if="!cancelDelete">Elimina</th>
<th ng-if="cancelDelete">Annulla</th>
</tr>

<tr ng-repeat="news in allNews | filter: deleteTitleText(news)">
<td>
<div ng-hide="editingData[news.id]">{{ news.title }}</div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.title" /></div>
</td>

<td>
<div ng-hide="editingData[news.id]">{{ news.arg }}</div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.arg" /></div>
</td>

<td>
<div ng-hide="editingData[news.id]"><input type="checkbox" disabled ng-model="news.isDeleted"></div>
<div ng-show="editingData[news.id]"><input type="checkbox" ng-model="news.isDeleted"></div>
</td>

<td>
<div ng-hide="editingData[news.id]"><button id="modify" class="btn btn-primary" ng-click="modify(news, $event)">Modifica</button></div>
<div ng-show="editingData[news.id]"><button id="accept" class="btn btn-success" ng-click="update(news)">Accetta</button></div>
</td>

<td>
<div ng-hide="editingData[news.id]"><button id="delete" class="btn btn-danger" ng-click="delete(news.id)">Cancella</button></div>
<div ng-show="editingData[news.id]"><button id="cancel" class="btn btn-danger" ng-click="cancelModify()">Annulla</button></div>
</td>
</tr>
</table>


The JS:

app.filter('deleteTitleText', function () {
return function (news) {
if (news.isDeleted == true) {
news.title = "<span><del>" + news.title + "</del></span>";
news.arg = "<span><del>" + news.arg + "</del></span>";
}
return news;
}
});


This is a good way to implement this kind of filter? For now I receive this error:
angular.js:13920 Error: [filter:notarray] Expected array but received: function ()
. Thanks

Answer

You need to alter you filter to expect the entire allNews array/object and work with that instead of just a single item in the list.

This might help.

For instance:

app.filter('deleteTitleText', function () {
    return function (allNews) {
        var filtered = [];
        angular.forEach(allNews, function(news) {
            if (news.isDeleted == true) {
                news.title = "<span><del>" + news.title + "</del></span>";
                news.arg = "<span><del>" + news.arg + "</del></span>";
            }
            filtered.push(news);
        });
        return filtered;
    }
});

Your ng-repeat should be changed from:

ng-repeat="news in allNews | filter: deleteTitleText(news)"

To:

ng-repeat="news in allNews | deleteTitleText"