1

Please guide me how do I push a new commodity object in the above loads object, by submiting a new form for commodity. The code I have tried is given below.

Note when I fill the form of commodity and submit to push in above json, it tells me undefined for loads.commodities.push

I have a complete sample JSON object (we call it loads), In which I have to push a commodity object. For new commodity I have an explicit form to add a new commodity details and push into existing loads object.

Loads Object:

{
    "loadStops": [
        {
            "companyId": 148,
            "companyCode": null,
            "legalName": "Frontier WHSE",
            "accessorialReason": null,
            "commodities": [{
                "id": 1,
                "commodity": "Food",
                "estWeight": 20000.00
            }]
        }
    ]
}

Display Table for viewing the loads data and Form to add New Commodity

<div ng-controller="FreightSaleCtrl">

<table>

    <tr>
        <th> Company Code </th> <th> Legal Name </th>
    </tr>
    <tr ng-repeat="theLoad in loads">
        <td> {{theLoad.companyCode}} </td>
        <td> {{theLoad.legalName}} </td>
    </tr>
    <tr>
        <td colspan="2">
            <table>
                <tr>
                    <th> Commodity </th> <th> EstWeight </th>
                </tr>
                <tr ng-repeat="cmdty in theLoad.commodities">
                    <td> cmdty.commodity </td>
                    <td> cmdty.estWeight </td>
                </tr>
            </table>
        </td>
    </tr>
    
    
</table>

</div>


<div>

<form ng-controller="FreightSaleCtrl">
    <input type="text" ng-model="commodityForm.commodity"/>
    <input type="text" ng-model="commodityForm.estWeight"/>
    <input type="submit" value="Add New Commodity"/>
</form>

</div>

My AngularJS controller:

(function() {
'use strict';
angular.module('bootstrapApp').controller('FreightSaleCtrl', FreightSaleCtrl);

    function FreightSaleCtrl($scope, $location, $http, $compile) {

    
        $scope.loads[0].commodities.push( $scope.commodityForm );
    
    }


});

My new commodity form that opens by clicking on the link given in the commodity table:**

<div class="modal fade" id="commoditiesModal" tabindex="-1" role="dialog"
    aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
    <form ng-controller="FreightSaleCtrl" id="commodity-form" role="form" novalidate>
        <div class="modal-content">
            <div class="modal-header modal-lg">
                <h5 class="modal-title" id="exampleModalLabel">
                    Add Commodity
                    <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </h5>
            </div>

            <div class="modal-body">
                
                    <div class="row">   <!-- row-1 -->
                        <div class="col-sm-3"> <!-- [0, 0] -->
                            <fieldset class="form-group">
                                <label id="fieldTitle">Commodity</label>
                                <input type="text" class="form-control" placeholder="" required data-error="Commodity required">
                                <div class="help-block with-errors"></div>
                            </fieldset>
                        </div>
                        <div class="col-sm-3"> <!-- [0, 1] -->
                            <fieldset class="form-group">
                                <label id="fieldTitle">Est. Weight</label>
                                <input type="text" class="form-control" placeholder="" required data-error="Est. weight required">
                                <div class="help-block with-errors"></div>
                            </fieldset>
                        </div>
                    </div>
            </div>

            <div class="modal-footer">
                <input type="reset" class="btn btn-warning btn-sm" value="Reset" />
                <button type="button" class="btn btn-danger btn-sm" ng-click="clear()"
                    data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-default btn-sm">
                    <i class="fa fa-check-square-o"></i> Submit
                </button>
            </div>

        </div>
        </form>
    </div>
</div>

The above form opens, when I click on this button: while the commodities displayed in the table:

enter image description here

The Commodity Form Modal itself enter image description here

4
  • There's no such thing as a JSON object. Please remove that from your list of phrases. What you are working with is just an object. JSON is a string format. Commented Mar 3, 2018 at 14:13
  • For this question, we need to see JavaScript code where you've attempted to add a new commodity to your array, or at least show us the code for your FreightSaleCtrl controller... Commented Mar 3, 2018 at 14:14
  • @MikeMcCaughan I am editing my question please check after a while Commented Mar 3, 2018 at 14:16
  • @MikeMcCaughan please see the updated question. Commented Mar 3, 2018 at 14:22

1 Answer 1

2
  • Every time the controller is specified, it will create new instance of that controller So it should be kept inside one controller
  • theLoad.commodities cannot be accessed as it is ouside the

<tr ng-repeat="cmdty in theLoad.commodities"> <td> cmdty.commodity </td> <td> cmdty.estWeight </td> </tr>

One way to solve this is to have add input boxes inside the table - for each loads

<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
  <link data-require="[email protected]" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script data-require="[email protected]" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
  <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.min.js"></script>

  <script>
    (function() {

      var app = angular.module("bootstrapApp", ['ui.bootstrap']);

      app.component('modalComponent', {
        templateUrl: 'myModalContent.html',
        bindings: {
          resolve: '<',
          close: '&',
          dismiss: '&'
        },
        controller: function($scope) {
          var $ctrl = this;
          $ctrl.$onInit = function() {
            $scope.theLoad = $ctrl.resolve.currentLoad;
          };

          $scope.ok = function() {
            $ctrl.close({
              $value: $scope.theLoad
            });
          };
        }
      });

      app.controller('FreightSaleCtrl', ['$scope', '$uibModal', function($scope, $uibModal) {

        $scope.loads = [{
          "companyId": 148,
          "companyCode": 1234,
          "legalName": "Frontier WHSE",
          "accessorialReason": null,
          "commodities": [{
            "id": 1,
            "commodity": "Food",
            "estWeight": 20000.00
          }, {
            "id": 2,
            "commodity": "Another",
            "estWeight": 160000.00
          }]
        }, {
          "companyId": 45,
          "companyCode": 7879,
          "legalName": "ASD froads",
          "accessorialReason": null,
          "commodities": [{
            "id": 10,
            "commodity": "Drinks",
            "estWeight": 5600.00
          }]
        }];



        $scope.openModal = function(load) {
          var modalInstance = $uibModal.open({
            animation: true,
            component: 'modalComponent',
            resolve: {
              currentLoad: function() {
                return load;
              }
            }
          }).result.then(function(currentLoad) {
            if (currentLoad) {
              var maxValue = Math.max.apply(Math, currentLoad.commodities.map(function(o) {
                return o.id;
              }))
              if (!maxValue) {
                maxValue = 0;
              }
              currentLoad.newCommodity.id = maxValue + 1;
              currentLoad.commodities.push(angular.copy(currentLoad.newCommodity));
              currentLoad.newCommodity = undefined;
            }
          }, function() {
            console.log('modal-component dismissed at: ' + new Date());
          });
        };

      }]);

    }());
  </script>
  <style></style>
</head>

<body ng-app="bootstrapApp">
  <div ng-controller="FreightSaleCtrl">

    <script type="text/ng-template" id="myModalContent.html">
      <div class="modal-header">
        <h3 class="modal-title" id="modal-title">Add Commodity !</h3>
      </div>
      <div class="modal-body" id="modal-body">
        <form name="testForm">

          <div class="form-group" ng-class="{ 'has-error' : testForm.commodity.$invalid && !testForm.commodity.$pristine }">
            <label>Commodity</label>
            <input type="text" name="commodity" ng-model="theLoad.newCommodity.commodity" placeholder="Commodity" ng-minlength="3" ng-maxlength="8" required/>
            <p ng-show="testForm.commodity.$error.required && !testForm.commodity.$pristine" class="help-block">commodity is required.</p>
            <p ng-show="testForm.commodity.$error.minlength" class="help-block">commodity is too short.</p>
            <p ng-show="testForm.commodity.$error.maxlength" class="help-block">commodity is too long.</p>
          </div>
          
          
          <div class="form-group" ng-class="{ 'has-error' : testForm.estWeight.$invalid && !testForm.estWeight.$pristine }">
            <label>estWeight</label>
            <input type="text" name="estWeight" ng-model="theLoad.newCommodity.estWeight" placeholder="EST Weight" ng-minlength="3" ng-maxlength="8" required/>
            <p ng-show="testForm.estWeight.$error.required && !testForm.estWeight.$pristine" class="help-block">estWeight is required.</p>
            <p ng-show="testForm.estWeight.$error.minlength" class="help-block">estWeight is too short.</p>
            <p ng-show="testForm.estWeight.$error.maxlength" class="help-block">estWeight is too long.</p>
          </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
        <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
      </div>
      </form>
    </script>

    <form name="commonForm">

      <table class="table">

        <tr>
          <th> Company Code </th>
          <th> Legal Name </th>
          <th> Commodity </th>
          <th> EstWeight </th>
        </tr>
        <tr ng-repeat="theLoad in loads">
          <td> {{theLoad.companyCode}} </td>
          <td> {{theLoad.legalName}} </td>
          <td colspan="2">

            <table class="table">
              <tr ng-repeat="cmdty in theLoad.commodities track by cmdty.id">
                <td>{{cmdty.id}} {{cmdty.commodity}} </td>
                <td> {{cmdty.estWeight}} </td>
              </tr>
              <tr>
                <td colspan="2">
                  <input class="pull-right" type="button" value="Add" ng-click="openModal(theLoad)" />
                </td>
              </tr>
            </table>

          </td>
        </tr>
      </table>

    </form>

  </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

9 Comments

I'm so much thankful to you... Thanks for your response.
could we replace these boxes with a form, because I also have to work on validation therefore I could use my <form> instead of these boxes, through which validation is satisfied, but if we do so, our commodity form will be nested to another form. That's the problem.
I want to use <form> instead of these boxes, and the form should open in a bootstrap modal. please see the updated question for my commodity form that opens inside a modal.
you helped me alot. I'm thankful to you. Just one more thing and I'm gonna accept your answer. How do I add validation on the fields in modal?
Thanks for your help. For the validation please see if it can help embed.plnkr.co/eZWqCJak5bhsAYV6Iqe8
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.