Ben
Ben

Reputation: 16641

View not updating after change to array in AngularJS

In AngularJS, I am trying to add a new item to an array. The item gets added correctly, but the display does not reflect the change.

Add new task:

 $scope.addNewTask = function() 
 {  
    console.log( "Before: " + $scope.tasks.length );

    $scope.newTask = [
        {
            id:     '3',
            title:  'Get answer'
        }
    ];

    $scope.tasks.push( $scope.newTask[0] );

    console.log( "After: " + $scope.tasks.length ); // one more than before
};

Task array:

$scope.tasks = [
    {
        id:     '1',
        title:  'Run into problem'
    },
    {
        id:     '2',
        title:  'Ask question'
    }
];

View:

<ul>
    <li ng-repeat="task in tasks>
        {{ task.id }} {{ task.title }}
    </li>
</ul>

While I can see on the console that the new item was added, the list is not updating to reflect the change.

Edit: Don't know if it makes any difference, but the function is called upon clicking the submit button of a form as follows:

<form class="newtask-form" ng-submit="addNewTask()">
    <input type="submit" name="submit" value="Add new task" />
</form>

Upvotes: 2

Views: 5319

Answers (2)

Ben
Ben

Reputation: 16641

So, I solved it. The problem was this: In my code, I set ng-controller manually outside of ng-view. However, through the router, the controller for the view was set to the same controller.

So I believe what happened is that I had two nested controller objects, one with the tasks that got changed through the form submit, and another one with the tasks that got displayed through the li.

Ultimately, it looks like I will need to restructure my application and start using services for my data rather than stuffing it all into my controller (any good introductions about services are appreciated). But at least now I have an idea what the problem was.

Upvotes: 3

Kassem
Kassem

Reputation: 8266

Try to use an ng-click on the input itself rather than ng-submit on the form.

    <form class="newtask-form">
        <input type="submit" name="submit" 
               ng-click="addNewTask()" value="Add new task" />
    </form>

Not sure if that should make a difference but it's the only thing I could think of (other than calling scope.$apply() which you've already did.

Upvotes: 1

Related Questions