AngularJS - how to force a scope to update (promise for array item)

前端 未结 2 1091
一整个雨季
一整个雨季 2020-12-08 12:43

I\'ve created a controller in Angular that looks like this (edited for brevity):

function AppCtrl($scope, $http, $loca         


        
相关标签:
2条回答
  • 2020-12-08 12:57

    Are you using the $scope.projects in a binding? Or somewhere else in the code?

    Asking because you're returning, and a promise is never changed by it's result, although you can bind promises directly to the HTML expecting it's contents. This happens because, internally, Angular seems to watch for it's result.

    So, if you're using this variable somewhere else, then you need to use $q.when($scope.projects). You will get a new promise that will be resolved instantly if it has already been resolved.

    0 讨论(0)
  • 2020-12-08 13:07

    As soon as the projects are loaded, you're using one of the items from the array projects[i], let's theoretically assume it's the object 0x1 in memory. The problem is that when a new item is loaded (let's assume 0x2), and you update the array, you're changing the object that resides in the array position (the 0x1), but $scope.project still references the now abandoned object 0x1. You can't just change it in the array, you have to modify it, so you don't need to rebind the $scope.project variable.

    The best solution is to change array[i] = newData to angular.extend(array[i], newData). This way, you gonna just change all properties of array[i], and as your $scope.project points to the same object in memory it will be updated.

    Anyway, I also believe you may want to change if(array[i] == object) { to if(array[i]._id === object._id) { and your equality comparisons (==) to strictly equality comparisons (===). This if suits better your cause, as the new created object is not the same as the old one.

    0 讨论(0)
提交回复
热议问题