1

I am having an array of objects inside the $scope. The object has the name and 'attributes' property of which the attributes is an object. I have a text field which I need to bind to a model which should be used to filter the state based on either the name or noOfCitizens. However, the below code is not filtering the items. Where I am going wrong.

I am working with Angularjs 1.5.8 version

//Inside the controller

$scope.states=[];   
    var mp = {};
    mp.name = "MP";
    mp.attributes= {
        "name":"MP",
        "noOfCitizens":"~ 900000"
    };

    var ts = {};
    ts.name = "TS";
    ts.attributes= {
        "name":"TS",
        "noOfCitizens":"~ 8000"
    };
    $scope.states.push(mp);
    $scope.states.push(ts);

<!-- Inside my html page -->
<div style="margin-left: 10px">
  <input type="text" ng-model="state.attributes['name']" placeholder="filter">
</div>
<div class="col-lg-3" ng-repeat="state in states | filter:state.attributes['name']">
  <h2>{{state.name}}</h2>
  <ul>
    <li>Name: {{state.attributes['name']}}</li>
    <li>No Of Citizens: {{state.attributes['noOfCitizens']}}</li>
  </ul>
</div>

1 Answer 1

2

Change your ng-model directive and the option passed to the filter pipe as follows,

ng-model="ctrl.stateFilter"

ng-repeat="state in ctrl.states | filter : ctrl.stateFilter"

Check the below code snippet.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);

function DefaultController() {
  var vm = this;
  vm.states = [];
  var mp = {
    name: "MP",
    attributes: {
      "name": "MP",
      "noOfCitizens": "~ 900000"
    }
  };

  var ts = {
    name: "TS",
    attributes: {
      "name": "TS",
      "noOfCitizens": "~ 8000"
    }
  };

  var vs = {
    name: "VS",
    attributes: {
      "name": "VS",
      "noOfCitizens": "~ 8000"
    }
  };

  vm.states.push(mp);
  vm.states.push(ts);
  vm.states.push(vs);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <div style="margin-left: 10px">
      <input type="text" ng-model="ctrl.stateFilter" placeholder="filter">
    </div>
    <div class="col-lg-3" ng-repeat="state in ctrl.states | filter : ctrl.stateFilter">
      <h2>{{state.name}}</h2>
      <ul>
        <li>Name: {{state.attributes.name}}</li>
        <li>No Of Citizens: {{state.attributes.noOfCitizens}}</li>
      </ul>
    </div>
  </div>
</div>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.