angularjs ngclick clear and search

Issue

Trying to solve a problem which looks very simple but hard to understand:-)

I have Json file from where I am trying to get the fetch the data using AngularJS, Based on the User Input (Name), Browser display only those results not the old ones.

names.json

{"name": {
  "Alan": [{ "Class":"1", "Books":"20"}],
  "Sam": [{ "Class":"2", "Books":"204"}],
  "John": [{ "Class":"4", "Books":"240"}],
   }
 }

Example:
Input: Alan

Output: Name: Alan , Class: 1, Books: 20.

I have managed to print the expected result with the following code:

names.js file:

var NamesApp = angular.module('NamesApp', [])
NamesApp.controller('NameCtrl', function($scope, $http){
$http.get('names.json').success(function(data) {
          $scope.getit = data;
        });
        $scope.results = [];
        $scope.findValue = function(userInput) { 
        angular.forEach($scope.getit.name, function(value, key) {
      if (key === userInput) {
        $scope.results.push({n: key, c: value[0].Class, b: value[0].Books});
      }

    });

    };
});

And my HTML file looks like this:

<body ng-controller="NameCtrl">
  <input type="text" ng-model="userInput">
  <button type="submit" ng-Click="findValue(userInput)">Find</button>
  <h3>Results</h3>
  <span ng-repeat="result in results">Name: {{result.n}} , Class: {{result.c}} , Books: {{result.b}}</span>
</body>

Problem:
When you search for the first time or after refreshing the page, you will get the results clean.

How should I clean the Search results, before searching for another name?

My Result section should always only the queried results, not the old results.

Solution

Reset your $scope.results before each search.

$scope.findValue = function(userInput) { 
        $scope.results = [];
        angular.forEach($scope.getit.name, function(value, key) {
      if (key === userInput) {
        $scope.results.push({n: key, c: value[0].Class, b: value[0].Books});
      }
    });
}

Answered By – Hamlet Hakobyan

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.