0

A quick question:

I'm creating a filter in angularjs to get dynamically a variable and to be used like this from frontend.

<div ng-if="(services | searchValue : 'type' : 'facebook').active == true">
...
</div>

This is the javascript.

.filter('searchValue', function () {
        return function (array, name_var, value) {
            angular.forEach(array, function(v, k) {
                if (v[name_var] == value) {
                    return v;
                }
            });
            return [];
        };
    })

Unfortunately even if the result was found it wasn't passed to the template.

If I'll use it like this:

{{(services | searchValue : 'type' : 'facebook')}}

This will get no value. Any suggestion?

1
  • I think it should be like (services | searchValue : 'type' ) Commented Jan 18, 2017 at 17:33

1 Answer 1

1

I've created a sample example for the info you've provided. Run the below example check. Hope this helps you.

I guess ng-if itself expects only the variable and not the expression. only provide the variable with value i.e (services | searchValue : 'type' : 'facebook').active not the expression.

var app = angular.module('application', []);

app.filter('customfilter', function() {
  return function(array, name_var, value) {
    var filteredArray = {};
    angular.forEach(array, function(v, k) {
      if (v[name_var] == value) {
        filteredArray = v;
        return false;
      }
    });
    return filteredArray;
  }

});
app.controller('sampleController', function($scope, $filter) {
  $scope.data = [{
    "type": "facebook",
    "active": false
  }, {
    "type": "linkedin",
    "active": false
  }, {
    "type": "twitter",
    "active": false
  }, {
    "type": "google",
    "active": false
  }];

  $scope.anotherdata = [{
    "type": "facebook",
    "active": true
  }, {
    "type": "linkedin",
    "active": false
  }];
});
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17"></script>

<body ng-app="application">
  <div ng-controller="sampleController">

    First div - Active : false
    <div ng-if="(data | customfilter:'type':'facebook').active">
      Your div content goes over here
    </div>
    <br>
    <br>Second div - Active : true
    <div ng-if="(anotherdata | customfilter:'type':'facebook').active">
      Second div rendered
    </div>
  </div>
</body>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.