2014-12-30 31 views
0

为什么$scope.events.push(data);更新范围和工厂?为什么我的范围更新我的工厂和我的工厂更新我的范围,当它不应该?

为什么EventFactory.setEvent(data);更新工厂和范围?

摘要:

$scope.events.push(data); //should only update scope but also updates factory 
EventFactory.setEvent(data); //should only update factory but also updates scope 

如果我没有这样的线都取消注释之一,然后我得到同样的效果做:

$scope.events.push(data); 
$scope.events.push(data); 

EventFactory.setEvent(data); 
EventFactory.setEvent(data); 

基本上$scope.events.push(data);EventFactory.setEvent(data);更新工厂和范围。

我想要$scope.events.push(data);只更新范围。我想EventFactory.setEvent(data);只更新工厂。

app.js(含工厂)

angular.module("EventListCtrl", []).controller("EventListController", function($scope, EventFactory, socket){ 

    $scope.events = []; 

    EventFactory.init().then(function(events){ 
     $scope.events = events; 
    }); 

    socket.on("event created", function(data){ 
     $scope.events.push(data); // should only update scope but updates factory as well 
     EventFactory.setEvent(data); // should only update factory but updates scope as well 
    }); 
}); 

我已经测试的代码

... 
app.factory("EventFactory", function($http){ 

    var events = []; 

    var init = function(){ 
     return $http.get("api/events", {cache:true}) 
     .then(
      function(response){ 
       events = response.data; 
       return response.data; 
      }); 
    }; 

    var getEvents = function(){ 
     return events; 
    }; 

    var setEvent = function(data){ 
     events.push(data); 
    }; 

    return { 
     init: init, 
     getEvents: getEvents, 
     setEvent: setEvent 
    } 
}); 
... 

EventListCtrl.js(控制器)和插座是没有问题的,也许已经采取了一些结合我还没有理解的地方。

任何帮助,非常感谢。

谢谢

+0

什么是你传递'socket'依赖在? –

+0

来自bfford的angular-socket-io https://github.com/btford/angular-socket-io – user2125471

回答

1

发生这种情况,因为你是在你的控制器使得$scope.events = events而不是$scope.events = angular.copy(events);

(你可以改为让副本你服务,这将是更DRY)

更清楚地说,这是因为你正在制作对象引用;不是对象克隆/副本。(数组技术上对象)

+0

感谢Cory我不知道这是真的,这是问题所在。 – user2125471

0

你要发送的“创建活动”插座事件给他人,可能你自己接受它也让你的范围也在更新

更超过

所有服务angularjs是单身人士

而且你只有一个副本的服务无处不在,这是如何工作的,当你改变一些东西在工厂它将被更新d其他地方也

+0

感谢A.B花时间回复,但我的问题是Cory发布的。 – user2125471

0

在EventListCtrl控制器你是做着做着浅拷贝:

$scope.events = events; 

其中两个对象都具有相同的参考。

为了使深拷贝出来的,角度为我们提供了复制()方法:

angular.copy(source, [destination]); 
source: The source that will be used to make a copy. Can be any type, including primitives, null, and undefined 
destination(optional): Destination into which the source is copied. If provided, must be of the same type as source. 

你的情况应该是:

$scope.events = angular.copy(events); 
相关问题