ng-model of an object

0

I have a controller:

function ItemsCrtl($scope) {

      $scope.items = [
        {id: 0, name: "PC"},
        {id: 2, name: "GEladeira"},
        {id: 3, name: "Fogao"},
        {id: 4, name: "cama"},
        {id: 5, name: "privada"},
        {id: 6, name: "sofá"}
      ]

    }

And in my html:

<div ng-controller="ItemsCrtl">    
<input type="text" ng-model="items.name">
     <ul>
      <li ng-repeat="item in items">
       {{item.id}} - {{item.name}}
      </li>
     </ul>
</div>

But ng-model does not work, it does not filter the list by the name of the item. How to do this when it is a list of objects.

    
asked by anonymous 05.03.2018 / 16:20

1 answer

1

I imagine your problem is at another point during the initialization process of your application.

The functional example below declares the function using the .controller() extension. Click Run to see it working.

The value to be searched is stored in $filtro . This value is then used in ng-repeat , specifying that this value should be compared to the contents of the name q property of each collection object.

angular.module('myApp', [])
.controller('ItemsCrtl', function($scope){
   $scope.items = [
        {id: 0, name: "PC"},
        {id: 2, name: "GEladeira"},
        {id: 3, name: "Fogao"},
        {id: 4, name: "cama"},
        {id: 5, name: "privada"},
        {id: 6, name: "sofá"}
      ]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
  <div ng-controller="ItemsCrtl">    
     <input type="text" ng-model="$filtro">
     <ul>
      <li ng-repeat="item in items | filter: {name: $filtro}">
       {{item.id}} - {{item.name}}
      </li>
     </ul>
  </div>
</div>
    
05.03.2018 / 17:18