Martijn
Martijn

Reputation: 24789

Angular: Push item to list doesn't update the view

When I push an item to an array, the view won't refresh the list.

table:

<tbody id="productRows">
    <tr data-ng-repeat="product in products | filter: search">
        <td>{{ product.Code}}</td>
        <td colspan="8">{{ product.Name}}</td>
    </tr>
</tbody>

form:

<form data-ng-submit="submitProduct()">
    Code:
    <br />
    <input type="text" required data-ng-model="product.Code"/>
    <br />
    <br />
    Naam:
    <br />
    <input type="text" required data-ng-model="product.Name"/>
    <br />
    <input type="submit" value="Opslaan" />
</form>

submitProduct in controller:

$scope.submitProduct = function () {
    console.log('before: ' + $scope.products.length);

    $scope.products.push({Code: $scope.product.Code, Name: $scope.product.Name});
    console.log('after:' + $scope.products.length);
    console.log($scope.products);

    $scope.showOverlay = false;
};

As you can see, I log the total items in the array and it behaves like I would expect. The only thing that doesn't do what I expect is the content of my table, that doesn't show the new value.

What do I have to do, so the new row is displayed in the table?

Upvotes: 7

Views: 17175

Answers (2)

Martijn
Martijn

Reputation: 24789

Thanks for the answer and the comments. The problem was at another place. In my routeProvider I had declared a controller. I also had a ng-controller directive in my div. So my controller gets executed twice. When I removed the ng-controller directive, everything was just working as it should be :)

Upvotes: 5

Brett Postin
Brett Postin

Reputation: 11375

I can't see the rest of your code, but make sure $scope.products is defined in your controller.

See this example.

The only addition I made to the code you provided was:

$scope.products = [];

If this doesn't help then please provide more information.

Upvotes: 5

Related Questions