为什么$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(控制器)和插座是没有问题的,也许已经采取了一些结合我还没有理解的地方。
任何帮助,非常感谢。
谢谢
什么是你传递'socket'依赖在? –
来自bfford的angular-socket-io https://github.com/btford/angular-socket-io – user2125471