我的服务中有我的模型,我的所有模型都在一个对象中,我希望能够通过将模型重新分配给一个空对象来重置我的模型,但它似乎不起作用,但如果我直接删除了一个属性。
如何在不删除每个属性,刷新页面或进行重大更改的情况下重置模型?
try:
raw_response = response.read().decode('utf8', errors='ignore')
except ConnectionResetError:
brokenlinksflag = 1
brokenlinks = articlelinks[j] + ' ConnectionResetError, ' + brokenlinks
continue
(function () {
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function (MyService) {
var _this = this;
_this.model = MyService.model;
_this.myService = MyService;
_this.deleteInService = function () {
MyService.functions.resetModel();
};
});
myApp.service('MyService', function () {
var obj = {};
obj.model = {x: 1};
obj.functions = {};
obj.functions.resetModel = function () {
//delete obj.model.x; //THIS WORKS!
obj.model = {x: 1}; //BUT THIS DOESN'T :(
};
return obj;
});
})();
谢谢。
编辑:执行_this.model = MyService.model这是不可能的,因为我与许多控制器共享我的服务
答案 0 :(得分:1)
我认为您的问题的一个解决方案是创建一个默认模型变量,如master
副本,并使用angular.copy
,其中两个参数在调用该方法时将模型重置为主版本。
请参阅angular.copy
文档here。您会注意到现场演示实际上显示了重置功能。</ p>
我已更新现场演示插件以显示我认为您需要的行为http://plnkr.co/edit/BJ...。
希望有所帮助!
<强> UPDATE :: 强>
可能的实施虽然需要测试,但如下所示;
myApp.service('MyService', function () {
var masterModel = {x: 1};
var obj = {
model: {x: 1},
functions: {
resetModel: function() {
angular.copy(masterModel, obj.model);
}
}
};
return obj;
});
答案 1 :(得分:1)
除了angular.copy
之外,另一种解决方案是不使用_this.model
并使用_this.myService.model
代替或将deleteInService
功能更改为
_this.deleteInService = function () {
MyService.functions.resetModel();
_this.model = MyService.model;
};
你遇到这个问题的原因是因为你正在做这样的事情:
service.model = foo;
controller.model = service.model; // implies controller.model = foo;
service.reset(); // => service.model = bar;
// But notice that controller.model still points to the old object foo
运行下面的代码段,看看我的意思。
(function () {
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function (MyService) {
var _this = this;
_this.model = MyService.model;
_this.serviceModel = MyService.model;
_this.myService = MyService;
_this.deleteInService = function () {
MyService.functions.resetModel();
_this.serviceModel = MyService.model;
};
});
myApp.service('MyService', function () {
var obj = {};
obj.model = {x: 1};
obj.functions = {};
obj.functions.resetModel = function () {
//delete obj.model.x; //THIS WORKS!
obj.model = {x: 1}; //BUT THIS DOESN'T :(
};
return obj;
});
})();
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="changingModelInService.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController as myCtrl">
<pre>myCtrl.model = {{myCtrl.model}}</pre>
<pre>myCtrl.serviceModel = {{myCtrl.serviceModel }}</pre>
<pre>myCtrl.myService.model = {{myCtrl.myService.model}}</pre>
<div><input ng-model="myCtrl.model.x"/></div>
<button ng-click="myCtrl.deleteInService()">Delete X in service</button>
</body>
</html>