Search code examples
mysqlangularjsnode.jsrestangularjs-http

NodeJS rest api with mysql cannot iterate on the output format


Guys I followed a tutorial about how to implement a rest api with node+express+mysql and here is a route from inside my code REST.js file:

router.get("/companies",function(req,res){
    var query = "SELECT * FROM ??";
    var table = ["company"];
    query = mysql.format(query,table);
    connection.query(query,function(err,rows){
        if(err) {
            res.json({"Error" : true});
        } else {
            res.json({"Companies" : rows});
        }
    });
});

and this is how I call them using angular:

sampleApp.controller('InstallController', function($scope, $http) {
    $http.get('http://localhost:3000/api/companies').
            success(function (data) {
                $scope.clients = data;
            });
}

and html

  <option ng-repeat="client in clients">{{client}}</option>

this is what I get as a response:

    {
  "Companies": [
    {
      "id": 1,
      "name": "GOLF"
    },
    {
      "id": 2,
      "name": "RENAULT"
    },
    {
      "id": 3,
      "name": "AUDI"
    },
    {
      "id": 4,
      "name": "MAZDA"
    }
  ]
}

My goal is to iterate on the result to populate a select tag with names. Bear with me please, I'm starting. Thank you :)


Solution

  • You should use below, but you could only have id value inside selectedClient when you select any value.

    <select ng-model="selectedClient">
        <option value="client.id" ng-repeat="client in clients.Companies">
          {{client.name}}
        </option>
    </select>
    

    Even better option would be using ng-options directive on select dropdown, so here you can select object instead of primitive value. Like you will have {"id": 1, "name": "GOLF" } object when you select GOLF option, whether as repeating option with ng-repeat has limitation to select primitive type value by it.

    <select ng-model="selectedClient" ng-options="client.name for client in clients.Companies"></select>