简体   繁体   中英

How to search item in database if not found in object in angular.js?

Trying to make ajax request when searched data is not found in object.

Html:-

Search programming languages: <input type="Text" ng-model="out.pl">
<div ng-controller="MyContRollEr">
   <table border="2">
       <tr>
           <td>Programming Language:</td>
           <td>Percentage:</td>
           <td>Salary:</td>
           <td>People:</td>
           <td>Started Date:</td>
       </tr>
     <tr ng-repeat="data in info | filter:out">
       <td>{{data.pl}}</td>
       <td>{{data.percent}}</td>
       <td>{{data.salary |currency:'Rs.'}}</td>
       <td>{{data.people | number :2}}</td>
       <td>{{data.date | date:"yyyy/MM/dd"}}</td>
    </tr>
  </table>

Controller:-

var app = angular.module('app',[]);
app.controller('MyContRollEr',function($scope) {
  var info = [
       {pl:'php',percent:'10%',salary:10000000,people:234524},
       {pl:'Java',percent:'20%',salary:9822200,people:234443},
       {pl:'python',percent:'10%',salary:8739300000,people:2345521)},
     ];
     $scope.info = info;
 });

My Function :-

  function sendRequest(){
     $http({
       method:'POST',
       url:'index.php',
       data:{search:'data'}
      }).then(function(data) {
        $scope.out = data;
      })
  }

How to do this combining my controller, function and model.

,This is where angular service comes into play. You should make a new file for both controllers and services. For the sake of simplicity though, you can just add the following code into your current file AFTER the controller.

   app.service('myService',function($http) {
       this.sendRequest = function() {
           $http({
               method:'POST',
               url:'index.php',
               data:{search:'data'}
           }).then(function (response) {
               console.log(response);
               return response.data; // Most APIs have the "data" in the response object. But you can take this out if the console log doesn't show that key in the object.
           })
       }
   )

Once that is done, you'll inject your service into your controller here:

    app.controller('MyContRollEr',function($scope, myService) { // Notice that the service is a parameter in controller now.

Next, lets call do the POST by hitting the service. Inside of your controller block, write the following:

     myService.sendRequest().then(function (response) {
         console.log(response);
     })

If you aren't using Gulp (or something similar), then you will need to add the service into your index.html(Or whatever file is your base html file) file just like you did(I assume) with your controller.

Let me know if you have any questions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM