Search code examples
javascripthtmlangularjsdomupdating

Why isn't my angularJS updating correctly in the DOM?


So, I'm working on an application with AngularJS routes and parameters. I have my controllers set up, and for some reason when I go to one of the pages my application isn't pulling the array from the angularJS code, nor adding in my items! Any ideas?

Here is my angular:

.controller("foodController", function ($scope) {
    $scope.addItem;
    $scope.foodItem = "";

    $scope.foodArray = ['Milk', 'PB&J'];

    //add items here
    $scope.addItem = function () {
        /*if ($scope.foodItem = '') {
            alert('What did the child eat?');
        } else {*/
        $scope.foodArray.push($scope.foodItem);
        $scope.foodItem = '';
    };
});

Here is my HTML:

<body ng-app="myApp" ng-controller="foodController">

<form ng-submit="addItem()">
    <h1>Food Chart</h1>
    <input type="text" placeholder="What did the child eat today?" ng-model="foodItem" />
    <button type="submit" id="submit">Submit</button>
</form>
{{ foodItem }}
<section>
    <h1>Food Log</h1>
    <tr ng-repeat="item in foodArray">
        <td> {{ item }}</td>
        <td>
            <button ng-click="removeItem(item)"> Remove Item</button>
        </td>
    </tr>
</section>

Thank you in advance!


Solution

  • You need a table to iterate over rows with your tr

    Try this instead:

    <div ng-controller="foodController">
      <form ng-submit="addItem()">
        <h1>Food Chart</h1>
        <input type="text" placeholder="What did the child eat today?" ng-model="foodItem"/>
        <button type="submit" id="submit">Submit</button>
      </form>
      {{ foodItem }}
      <section>
        <h1>Food Log</h1>
        <table>
          <tbody>
          <tr ng-repeat="item in foodArray">
            <td> {{ item }}</td>
            <td>
              <button ng-click="removeItem(item)"> Remove Item</button>
            </td>
          </tr>
          </tbody>
        </table>
      </section>
    </div>