Fill form fields with API data

Asked

Viewed 401 times

-1

Good morning, I have a form where the user enters the code of a product. When entering the code an API is triggered and it returns the data of the informed product.

My doubt now is how to make the form fields be filled with the data that the API returned. Someone could help me, I’d be grateful.

NOTE: backend is in Nodejs and front is in Angularjs

This is the code that returns the API:

   vm.selectAtivoPlaca = function () {
        const vm = this

        const url = `http://localhost:3000/api/produto?placa=${vm.ativo.placa}`
        console.log(url)

        $http.get(`${url}&idempresa=${JSON.parse(localStorage.getItem("_app_user")).user.idempresa}&status=true`).then(function (response) {
            vm.ativocadastros = response.data
            console.log(vm.ativocadastros)
        })
    }

Here is the form field where the user enters the code.

<div class="col-xs-12 col-sm-6 col-md-12">
    <p><label>Placa</label></p>
    <input type="text" ng-model="atiCtrl.ativo.placa" class="form-group" ng-blur="atiCtrl.selectAtivoPlaca()" />
</div>

Aqui é o retorno da API

1 answer

0

You will create the inputs of the fields you want, each with its own ng-model.

For example: <input type="text" ng-model="marca" class="form-group" />

Within the then you enter the value into the variables ( brand name is just an example, you adapt to your reality):

  vm.selectAtivoPlaca = function () {
      const vm = this

      const url = `http://localhost:3000/api/produto?placa=${vm.ativo.placa}`
      console.log(url)

      $http.get(`${url}&idempresa=${JSON.parse(localStorage.getItem("_app_user")).user.idempresa}&status=true`)
        .then(function (response) {
          vm.ativocadastros = response.data
          vm.marca = vm.ativocadastros.marca
          console.log(vm.ativocadastros)
        })

That way, the value goes to the ng-model that you want.

Obs.: It is a good practice to put point and comma ; at the end of each line. It is safer ;)

Browser other questions tagged

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