Angularjs不会更新异步模型更改的视图

Angularjs does not update view on async model changes

本文关键字:视图 模型 异步 更新 Angularjs      更新时间:2023-09-26

由于模型和视图之间缺乏同步,我在尝试将模型与控制器分离时遇到了问题。我环顾四周,发现大多数时候申请都能解决问题。然而,apply对我来说根本不起作用(无论是从根作用域还是使用chrome的相关作用域调用时)。在这个链接中,我有一个关于我的程序中几乎所有问题的演示,但我的程序没有间隔,而是有异步请求,或者只是复杂的函数,这些函数似乎也被angular错过了。在演示中,我有4个变量应该在视图中更新。一个由作用域监视,另一个通过回调更新,另一种完全依赖于模型,还有一个通过将作用域本身传递给服务来更新。在这4个中,只有回调和将作用域传递给服务是更新视图的,即使我在每次更新后运行apply(在每次执行$interval后已经运行的回调之上)也是如此。我试图避免的是,每当我的数据因转换而更改时,都会使用大量的回调或承诺,因为我有很多不同的转换。有没有办法做到这一点,或者回调和承诺是唯一的选择?

var test = angular.module("tpg",[]);
test.controller("myctrl", function($scope, $interval, service)
{
  $scope.$watch(service.list.name, function()
  {
    $scope.name=service.list.name;
  });
  $scope.op=service.list.op;
  $scope.call=service.list.call;
   $scope.scope=service.list.test;
  $scope.update=function()
  {
    service.getValues(function(op){$scope.op=op}, $scope);
  };
}).factory("service", function($interval, $rootScope)
{
  return {
    list:{name:"OPA", op:"TAN", call:"1", test:"scope"},
    getValues:function(callback, $scope)
    {
      var self=this;
       var interval = $interval(function()
        {
          if(self.count>2)
          {
            $interval.cancel(interval);
            self.count=0;
            self.list={name:"OPA", op:"TAN", call:"1"};
          }
          else
          {
            self.list=self.values[self.count];
            callback(self.list.op);
            $scope.scope=self.list.test;
            console.log(self.list);
            self.count++;
          }
          $rootScope.$$phase || $rootScope.$apply();
        },2000);

    },
    values: [{name:"guy", op:"ungly", call:"2", test:"scope1"}, {name:"TAL", op:"stink", call:"3", test:"scope2"}, {name:"tes", op:"test", call:"4", test:"scope3"}],
    count:0
  };
});

您只需要从服务返回一个回调函数$范围$在处理角度服务时不需要apply,因为服务本身会触发摘要运行。因此,我修改了代码,删除了$apply和promise,并从服务返回了一个简单的回调,然后该服务使用返回的数据更新视图。

代码:

$scope.update=function()
  {
    service.getValues(function(data){
      $scope.name = data.name;
      $scope.op=data.op;
    $scope.call=data.call;
   $scope.scope=data.test;
    });
  };
}).factory("service", function($interval, $rootScope)
{
  return {
    list:{name:"OPA", op:"TAN", call:"1", test:"scope"},
    getValues:function(callback){
      var self=this;
       var interval = $interval(function()
        {
          if(self.count>2)
          {
            $interval.cancel(interval);
            self.count=0;
            self.list={name:"OPA", op:"TAN", call:"1"};
          }
          else
          {
            self.list=self.values[self.count];
            console.log(self.list);
            callback(self.list);
            self.count++;
          }
        },2000);
    },
    values: [{name:"guy", op:"ungly", call:"2", test:"scope1"}, {name:"TAL", op:"stink", call:"3", test:"scope2"}, {name:"tes", op:"test", call:"4", test:"scope3"}],
    count:0
  };
});

工作plunkr