简体   繁体   中英

Ng-show not filtering correctly

I am trying to remove my listing and only want it show up when I select an option.

I have this snippet and tried using ng-show:selectedCompany

  <tr ng-show="selectedCompany" data-ng-repeat="client in filtered = (clients | companyFilter:selectedCompany)">

It filters correctly when I click all the options but wont work when I click one. Basically it should display the json data.

Demo: http://jsfiddle.net/s2bg6ugo/

It has to do with truthiness and how angular watches for changes. [] == false, so it will not show when it's first loaded. But then you add an id to the array, so now [1] != false. However, because angular is just watching the array itself and not its contents, there has been no change (it's the same array), hence it doesn't update until the scope has another reason to do a hard check.

Instead put this in your ng-show:

ng-show="selectedCompany.length"

 angular.module('App.filters', []).filter('companyFilter', [function () { return function (clients, selectedCompany) { return clients.filter(function(obj){ return selectedCompany.indexOf(obj.company.id) > -1; }) /*if (!angular.isUndefined(clients) && !angular.isUndefined(selectedCompany) && selectedCompany.length > 0) { var tempClients = []; angular.forEach(selectedCompany, function (id) { angular.forEach(clients, function (client) { if (angular.equals(client.company.id, id)) { tempClients.push(client); } }); }); return tempClients; } else { return clients; }*/ }; }]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM