ng-model of an object

Asked

Viewed 430 times

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 item name. How to do in this case when it is a list of objects.

  • And the controller?

  • Not much has changed, but there’s the controller

1 answer

1


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

The functional example below declares the function using the extension .controller(). Click on Execute 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 content of the property name of each object in the collection.

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>
<div ng-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>

  • But what about the part that displays in the list only items that match the word typed? <input type="text" ng-model="items.name">

  • @Felipecoelho I copied the wrong step of the example, thank you for pointing out my mistake! I updated with the correct answer.

  • It worked!! Excellent thanks!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.