V
V
vladimir22092016-12-23 08:41:57
API
vladimir2209, 2016-12-23 08:41:57

How to get data from form and send it with put method in api?

How to get data from form and send it with put method in api?
Main file index.html

<!DOCTYPE html>
<html lang='en' ng-app='userApp'>
<head>
  <meta charset="utf-8">
  <title>Angular App</title>

  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js'></script>
  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-route.min.js'></script>
  <script src='app/app.js'></script>
  
</head>
<body>
<ng-view></ng-view>
</body>
</html>

It is necessary to develop a single-page application using AngularJS, consisting of two screens-pages.
On the index page, place a table with a list of elements received from the API:
curl -X GET " http://000.000.000.000:8081/test/users "
When one element is selected in the table, the Edit button appears, when clicked, it takes you to the page editing the selected item.
This screen should have a Save button that, when clicked, saves the element and returns to the index page.
Saving changes is implemented via API:
curl -X PUT " http://000.000.000.000:8081/test/users/edit" -d '{ "id": "8a999e24-0819-4110-a7ba-247c0a52b138", "name": "Chanda Kochhar", "phone": "+79150000002", "balance": 100.0 }
' Angular services such as $http/$resource, $location, $route, promises, controllers, directives should be
used.So far I have only done that I get all users and on hover the button appears if I click, I get into the edit controller and here don't know what to do, first day with angular
'use strict';

var userApp = angular.module('userApp',['ngRoute']);

userApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
  
  $routeProvider
    .when('/', {
      templateUrl:'template/home.html',
      controller:'UserListCtrl'
    })
    .when('/edit/:userId', {
      templateUrl:'template/edit.html',
      controller:'EditUserCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
}]);

userApp.controller('UserListCtrl',['$scope', '$http', '$location', function($scope, $http, $location){
  $scope.title = 'Users';
  $http({
    method: 'GET', 
    url: 'http://9000.000.000.0008081/test/users'
  }).then(function successCallback(response) {
    $scope.users = response.data;
  }, function errorCallback(response) {
  console.log(response);
  });
}]);

userApp.controller('EditUserCtrl',['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){
  $scope.title = 'Edit User ' + $routeParams.userId;
  $scope.userId = $routeParams.userId;

}]);

Help pliz)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kumanin, 2016-12-23
@vladimir2209

Use $resource

var app = angular.module('myApp', []);

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
  
  $routeProvider
    .when('/', {
      templateUrl:'template/home.html',
      controller:'UsersCtrl'
    })
    .when('/edit/:userId', {
      templateUrl:'template/edit.html',
      controller:'EditCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
}]);

// Создаем фабрику для работы с ресурсом пользователей
app.factory('UserResource', function ($resource){
    // Возвращаем ресурс, ссылка на документацию выше
    return $resource(
      '/test/users/:action',  // роут для работы
      {id: '@id'}, // поле идентификатор
      {
        update: { // переопределим метод update
          method: 'PUT', // тип запроса
          params: {action: 'edit'} // параметр action в роуте
        },
      }
    );
  });

// Контроллер списка пользователей
app.controller('UsersCtrl', function ($scope, UserResource) {
  // запрос на список пользователей
  $scope.users = UserResource.query();
});

// Контроллер редактирования пользователя
app.controller('EditCtrl', function ($scope, UserResource, $routeParams) {
  // Загружаем текущего пользователя по ид из роута
  $scope.user = UserResource.get({id: $routeParams.userId});

  // Функция сохранения пользователя, form - объект формы
  $scope.saveUser = function(form){
    // Вызываем переопределенный метод update
    UserResource.update($scope.user)
      .$promise
      // Ловим ошибки
      .catch(function(err){
        console.error(err);
      });
  };
});

Content template/home.html
<ul>
  <li ng-repeat="user in users"><a href="/edit/{{user.id}}">{{user.name}}</a></li>
</ul>

The content of template/edit.html
<form class="form" name="form" ng-submit="saveUser(form)" novalidate>
  <input type="text" ng-model="user.name">
  <button class="btn btn-default" type="submit" ng-disabled="form.$invalid">Сохранить</button>
</form>

index.html
<!DOCTYPE html>
<html lang='en' ng-app='myApp'>
<head>
  <meta charset="utf-8">
  <title>Angular App</title>

  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js'></script>
  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-route.min.js'></script>
  <script src='app/app.js'></script>
  
</head>
<body>
<ng-view></ng-view>
</body>
</html>

UPD: Added form
UPD2: Added comments
UPD3: https://plnkr.co/edit/LTTkrd3NbSSxC7ZKw9GJ?p=preview

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question