Angular $watch数组并从服务器更新

Angular $watch array and update from server

本文关键字:服务器 更新 数组 watch Angular      更新时间:2023-09-26

我正在使用以下代码深入观察一个名为$scope.route.waypoints的数组:

$scope.$watch('route.waypoints',  _.debounce(function (prev, cur) {
    if(!$scope.initialized) return;
    $scope.saveRoute(true);
    console.log('route waypoints DEEP check');
}, 500), true)

在我的saveRoute方法I PUT收集到服务器。

我想做的是从服务器返回后,我想再次更新我的路径点集合中的一些属性。但是当我使用以下命令更新时:

if(data.linked && data.linked.waypoints.length){
        $scope.route.waypoints = data.linked.waypoints;
}else{
        $scope.route.waypoints = [];
}
$scope.route.days = data.routes[0].days;

$watch再次被调用,整个过程重新开始。我怎样才能避免呢?我尝试使用$scope标志,但似乎它们又被忽略了。

您可以对这些数据使用不同的变量。例如,对于来自服务器的数据,你可以使用

$scope.route.waypoints  

对于本地域数据,您可以使用另一个域,例如:

$scope.route.waypointsData

在这种情况下你将有更多的控制因为你的服务器数据和你的本地数据将被分开

更新1

所以我的建议是

$scope.$watch('route.waypoints',  _.debounce(function (prev, cur) {
  //update data in this place  $scope.route.waypointsData 
}, 500), true)

然后也打开监视器

$scope.$watch('route.waypointsData ',  _.debounce(function (prev, cur) {
  // do your PUT method in that place 
}, 500), true)

和在ng-repeat中使用waypointsData。您正在手动同步模型之间的数据。

我通过扔掉$watches解决了这个问题。在阅读了这篇优秀的文章:http://www.benlesh.com/2013/10/title.html之后,我致力于将所有的指令都转移到ng-change指令中,并在必要时执行。$watches引入了一个不可测试的魔法,这就是我的问题的根源,它不再是可读的了。