角点符号更好的解释 [英] angular dot notation better explanation

查看:114
本文介绍了角点符号更好的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关使用AngularJS轮询数据的解决方案,我在这里找到了在stackoverflow上.

I was looking for a solution about polling data using AngularJS and I found here at stackoverflow.

在此解决方案中(如下所示),它使用了一个javascript对象来返回响应(data.response),如果我尝试将该data对象替换为一个简单的javascript数组,它不起作用,我想确切地知道为什么我需要使用点符号,为什么一个数组不起作用? (这将是很棒的链接或示例说明)

In this solution (shown bellow) it is used a javascript object to return the response (data.response) and if I try to replace that data object for a simple javascript array it doesn't work, I would like to know exactly why I need to go with dot notation and why a single array doesn't work? (It would be great links or explanation with examples)

app.factory('Poller', function($http, $timeout) {
  var data = { response: {}, calls: 0 };
  var poller = function() {
    $http.get('data.json').then(function(r) {
      data.response = r.data;
      data.calls++;
      $timeout(poller, 1000);
    });      
  };
  poller();

  return {
    data: data
  };
});

尝试总结我的目标(我想真正理解的东西):var data = { response: {}, calls: 0 };在哪里可能是var data = {};,然后response.data会直接设置为数据data = r.datareturn {data: data};,为什么我需要依靠点表示法吗?

Trying to summarize my goal (what I want to really understand): where is var data = { response: {}, calls: 0 }; could be var data = {}; and then the response.data would be setted directly to data data = r.data and return {data: data};, why do I need to rely on dot notation?

推荐答案

假设我们以这种方式更改工厂:

Let's say if we change the factory in this way:

app.factory('Poller', function($http, $timeout) {
  var d = {};
  var poller = function() {
    $http.get('data.json').then(function(r) {
      d = r.data;
      $timeout(poller, 1000);
    });
  };
  poller();

  return d;
});

在控制器中,语句$scope.data = Poller;将d对象分配给$ scope.data,因此初始化后的对象关系是这样的

In the controller, the statement $scope.data = Poller; assign d object to $scope.data, so the object relationship is like this after the initialization

$scope.data -> d -> r.data

在1秒钟内再次调用poller()时,d将被新对象替换,因此对象关系将变为

When poller() is called again in 1 sec, d is replaced with an new object, so the object relationship will be

$scope.data -> d* -> r.data (d* is a new object)

由于d *是一个具有不同原型的全新对象,因此无法跟踪r.data,因此angularjs的数据绑定将被破坏.

so the angularjs's data binding will be broken since there is no way to trace to the r.data since d* is a brand new object with different prototype.

使用点表示法,在初始化之后,对象关系永远不会改变,因为对poll()的定期调用不会创建新的对象d,而只是不断使用新的r.data对象更新响应字段.

With dot notation, after the initialization the object relationship never changes since the periodic calls to poll() doesn't create new object d but it just keeping updating the response field with new r.data object.

$scope.data -> d.response -> r.data

这篇关于角点符号更好的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆