basicFoodEditor.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * A pane that displays/edits basic food objects
  3. */
  4. (function() {
  5. (function() {
  6. try {return angular.module('ieat.ui.editors')}
  7. catch {return angular.module('ieat.ui.editors', ['ndbDatabase','Units'])}}
  8. )().component('basicFoodEditor', {
  9. templateUrl: 'static/templates/basicFoodEditor.html',
  10. bindings: {
  11. ndbKey: '@',
  12. food: '<'
  13. },
  14. controller: [
  15. '$scope', '$q', 'NDBList', 'NDBWeight', 'NDBNutrDef', 'Unit',
  16. function($scope, $q, NDBList, NDBWeight, NDBNutrDef, Unit) {
  17. var self = this;
  18. $scope.units_symbol = {};
  19. Unit.primary(function(units) {
  20. units.forEach(function(elm) {
  21. $scope.units_symbol[elm.type] = elm.symbol;
  22. });
  23. });
  24. NDBNutrDef.query(function(data) {
  25. $scope.nutrients = data.reduce(function(r, n) {
  26. r[n.nutr_no] = {name: n.nutr_desc, unit: n.unit};
  27. return r;
  28. }, {});
  29. });
  30. this.$onInit = function() {
  31. $scope.categories = NDBList.get({
  32. key: self.ndbKey,
  33. type: "g"
  34. });
  35. var getCanidateUnit = function(weight, units) {
  36. return units.find(function(u) {
  37. var w = weight.msre_desc.toLowerCase();
  38. return u.type == "volume" &&
  39. (w == u.symbol.toLowerCase()
  40. || u.aliases.some(function(a) {
  41. return w == a.toLowerCase();
  42. }));
  43. });
  44. };
  45. if (!self.food.density) {
  46. $q.all([
  47. NDBWeight.query({ndbno: self.food.ndbno}).$promise,
  48. Unit.query().$promise
  49. ]).then(function(res) {
  50. for (var i = 0; i < res[0].length; i++) {
  51. var w = res[0][i];
  52. var unit = getCanidateUnit(w, res[1]);
  53. if (unit) {
  54. self.food.density =
  55. w.gm_wgt / (w.amount * unit.conversion);
  56. return;
  57. }
  58. }
  59. }, function() {
  60. // TODO: Error handling
  61. console.err("Failed to get weight information.")
  62. });
  63. }
  64. if (!self.food.unit_type) {
  65. self.food.unit_type = "Mass";
  66. self.food.dry = true;
  67. }
  68. };
  69. }]
  70. });
  71. })();