Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Martijn Avatar asked May 16 '13 14:05

Martijn


2 Answers

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.

like image 95
Brett Postin Avatar answered Sep 22 '22 19:09

Brett Postin


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 :)

like image 27
Martijn Avatar answered Sep 21 '22 19:09

Martijn