自动更新范围变量angularjs变量、自动更新、范围、angularjs

2023-09-13 03:25:26 作者:祭岛离梦

我目前正在与AngularJS播放。我想退货,从服务,一个变量,将让当它改变了范围,知道了。

I'm currently playing with AngularJS. I'd like to return, from a service, a variable that will let the scope know when it has changed.

要说明这一点,看看这个例子从www.angularjs.org电线建立一个后端。粗略地说,我们可以看到以下内容:

To illustrate this, have a look at the example from www.angularjs.org, "Wire up a backend". Roughly, we can see the following:

var projects = $firebase(new Firebase("http://projects.firebase.io"));
$scope.projects = projects;

在此之后,到项目对象所做的所有更新(通过更新,无论是本地或远程)将在其范围是绑定到视图自动反映。

After this, all updates made to the projects object (through updates, be it locally or remotely) will be automatically reflected on the view that the scope is bound to.

我如何能实现我的项目中一样吗?在我的情况,我想从一个服务返回一个自我更新变量。

How can I achieve the same in my project? In my case, I want to return a "self-updating" variable from a service.

var inbox = inboxService.inboxForUser("fred");
$scope.inbox = inbox;

让什么样的机制在 $范围知道它应该更新?

编辑:为了响应的建议,我想一个基本的例子。我的控制器:

In response to the suggestions, I tried a basic example. My controller:

$scope.auto = {
    value: 0
};

setInterval(function () {
    $scope.auto.value += 1;
    console.log($scope.auto.value);
}, 1000);

和,在我看来的话:

<span>{{auto.value}}</span>

不过,这只是显示为0。我在做什么错了?

Still, it only displays 0. What am I doing wrong ?

推荐答案

我做了一个演示plunker: http://plnkr.co/edit/dmu5ucEztpfFwsletrYW p = preVIEW 结果我使用 $超时伪造的更新。

UPDATE:

I made a demo plunker: http://plnkr.co/edit/dmu5ucEztpfFwsletrYW?p=preview I use $timeout to fake updates.

的技巧是使用普通的JavaScript引用:

The trick is to use plain javascript references:

您需要将对象传递给范围。您不能覆盖​​对象,只需更新或扩展它。如果你这样做覆盖它,你失去了绑定。如果您使用 $ HTTP 会引发消化你。因此,每当发生变化时,范围变量引用同一对象被在服务更新,并且所有的观察者将与摘要被通知。据我所知,这是如何 $火力&安培; Restangular 工作如果你做多的更新,你需要有重置属性的方法。既然你坚持在应用程序对象的引用,你需要知道内存泄漏。 You need to pass an object to the scope. You mustn't override that object, just update or extend it. If you do override it, you lose the "binding". If you use $http it will trigger a digest for you. So, whenever a change occurs, the scope variable reference to same object that gets updated in the service, and all the watchers will be notified with a digest. AFAIK, That's how $firebase & Restangular work. If you do multiple updates you need to have a way of resetting properties. Since you hold a reference to an object across the application, you need to be aware of memory leaks.

服务:

app.factory('inboxService', function($http){

  return {
    inboxForUser: function(user){

      var inbox = {};

      $http.get('/api/user/' + user).then(function(response){
        angular.extend(inbox, response.data);
      })

      return inbox; 
    }
  };
});

控制器:

app.controller('ctrl', function(inboxService){
  $scope.inbox = inboxService.inboxForUser("fred");
});