سؤال

I need to filter an array that shown below by "all permission value" to send it on the server. It is an example. Thanks for any help.
<!DOCTYPE html>
    <html ng-app>
    <head>
        <script src="./angular.js"></script>
    <script>

        function MainCtrl($scope) {
            $scope.accounts = [{ name: 'KL', company: 'Alpha', permission: 'all'},
                               { name: 'Jem', company: 'Altes', permission: 'no' },
                               { name: 'Osama', company: 'Solar', permission: 'no' },
                               { name: 'Victor', company: 'Osteriks', permission: 'all' }];

            // I'd like to get here a filtered array by "all permission" from the View block filter

            $scope.filteredAccounts = // [ { name: 'KL', company: 'Alpha', permission: 'all'},
                                    //  { name: 'Victor', company: 'Osteriks', permission: 'all' }];
        }
    </script>
    </head>
    <body ng-controller="MainCtrl">
        <div ng-repeat="account in accounts | filter: { permission: 'all' }">
            <p>{{ account.name }}</p>
        </div>
    </body>
    </html>
هل كانت مفيدة؟

المحلول

I didn't feel like including underscore or lodash in my project just because i wanted the findWhere function so i added it to angular myself:

simply include this outside of angular and change the "angular.element(document)" to the element you booted your app on.

angular.findWhere = function(collection,search) { var $filter = angular.element(document).injector().get("$filter"), refined = $filter('filter')(collection,search); return refined[0]; }

then you just use it like this:

angular.findWhere($scope.accounts,{permission: 'all'});

نصائح أخرى

Most simple way is use lodash and write

$scope.filteredAccounts = _.where($scope.accounts,{permission: 'all'});

You can write custom filters in AngularJS. Here is a link to a document that talks about how to create one: https://docs.angularjs.org/tutorial/step_09

Your custom filter might look something like this:

myApp.filter('permissionFilter', function () {
    return function (accounts, permission) {
        var filtered = [];
        angular.forEach(accounts, function (account) {
          if (account.permission === permission) {
            filtered.push(account);
          }
        });
        return filtered;
    };
});

And the usage would be something like this:

  <div ng-controller="MainController">
    <div ng-repeat="account in accounts | permissionFilter:'all'">
      <p>{{ account.name }}</p>
    </div>
  </div>

This would allow you to use this filter to filter any kind of permission. In other words, you can change 'all' to 'no' and it will return Jem and Osama. You could take that a step further and bind to the filter variable, so you could let the user decide what they wanted to filter based on.

Here is a Plunker with a working example.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top