details.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const _ = require('lodash')
  2. const app = require('../../app')
  3. /**
  4. * @param {CrudPagesOptions} opts
  5. */
  6. const details = (opts) => {
  7. const defaultInput = column => html`
  8. <md-input-container>
  9. <label>${column.titleName}</label>
  10. <input type="${column.type || 'text'}" ng-model="model.${raw(column.camelName)}" />
  11. </md-input-container>
  12. `
  13. app.component(`app${opts.pascalName}DetailsPage`, {
  14. template: html`
  15. <app-user-area>
  16. <h1>{{ctrl.isNew ? 'New ${opts.titleName}' : '${opts.titleName} Details'}}</h1>
  17. <form name="form" ng-submit="ctrl.submit()">
  18. ${opts.columns.map(c => c.input || defaultInput(c))}
  19. <div>
  20. <md-button type="submit" class="md-raised md-primary">Submit</md-button>
  21. </div>
  22. </form>
  23. </app-user-area>
  24. `,
  25. controllerAs: 'ctrl',
  26. controller: function(api, $scope, $routeParams, $mdToast, $location) {
  27. this.isNew = $routeParams.id === 'new'
  28. const crud = api.crud(opts.apiPrefix)
  29. let original
  30. if (this.isNew) {
  31. original = {}
  32. $scope.model = Object.create(original)
  33. } else {
  34. crud.read($routeParams.id).then(model => {
  35. original = model
  36. $scope.model = Object.create(original)
  37. })
  38. }
  39. this.submit = async () => {
  40. try {
  41. if (this.isNew) {
  42. await crud.create($scope.model)
  43. } else {
  44. const obj = {}
  45. for (var key in $scope.model) {
  46. if ($scope.model.hasOwnProperty(key)) {
  47. obj[key] = $scope.model[key]
  48. }
  49. }
  50. await crud.update(original.id, obj)
  51. }
  52. $mdToast.showSimple(`${opts.titleName} saved.`)
  53. $location.url(opts.appPrefix)
  54. } catch (err) {
  55. console.error(err)
  56. $mdToast.showSimple(`Could not save ${opts.titleName}: ${err.message || err}`)
  57. }
  58. }
  59. }
  60. })
  61. }
  62. module.exports = details