I have an object on some controller's scope, bound to some inputs on the accompanying view. I want to share the data in that object with other controllers, so they can read it, but they should not be able to modify it.
我在某个控制器的作用域上有一个对象,绑定到随附视图上的一些输入。我想与其他控制器共享该对象中的数据,因此他们可以读取它,但是他们不能修改它。
It seems to me, if it put the model in a service/factory, I either allow or prevent all modification. Same thing if I put it on the rootscope.
在我看来,如果它将模型放在服务/工厂中,我要么允许或阻止所有修改。如果我把它放在rootcope上也一样。
What would be the connonical way of doing something like this?
做这样的事情的方法是什么?
2 个解决方案
#1
0
You can put the model in a service/factory, and assign getter/setter functions to it, something like:
您可以将模型放在服务/工厂中,并为其分配getter / setter函数,例如:
angular.factory('testFactory', [function(){
var _yourModel = {}
return {
yourModel: function(newValue){
if(newValue){
_yourModel = newValue
}else{
return angular.copy(_yourModel) //This will return a clone of _yourModel
}
}
}
}])
//In your controller
$scope.model = testFactory.yourModel();
#2
0
Just for a sake of this discussion . If you use $rootscope
to store your data globally like $rootscope.data()
. For instance, if you define $rootScope.data()
and in a controller you define a function $scope.data()
because you forget about the first created data()
, something will certainly go wrong.
只是为了讨论这个问题。如果你使用$ rootscope来全局存储你的数据,比如$ rootscope.data()。例如,如果您定义$ rootScope.data()并在控制器中定义函数$ scope.data(),因为您忘记了第一个创建的数据(),肯定会出错。
So best way to use this kind of scenario angular service
is better also please bear with my english.
所以最好的方式来使用这种场景角度服务更好也请用我的英语。
#1
0
You can put the model in a service/factory, and assign getter/setter functions to it, something like:
您可以将模型放在服务/工厂中,并为其分配getter / setter函数,例如:
angular.factory('testFactory', [function(){
var _yourModel = {}
return {
yourModel: function(newValue){
if(newValue){
_yourModel = newValue
}else{
return angular.copy(_yourModel) //This will return a clone of _yourModel
}
}
}
}])
//In your controller
$scope.model = testFactory.yourModel();
#2
0
Just for a sake of this discussion . If you use $rootscope
to store your data globally like $rootscope.data()
. For instance, if you define $rootScope.data()
and in a controller you define a function $scope.data()
because you forget about the first created data()
, something will certainly go wrong.
只是为了讨论这个问题。如果你使用$ rootscope来全局存储你的数据,比如$ rootscope.data()。例如,如果您定义$ rootScope.data()并在控制器中定义函数$ scope.data(),因为您忘记了第一个创建的数据(),肯定会出错。
So best way to use this kind of scenario angular service
is better also please bear with my english.
所以最好的方式来使用这种场景角度服务更好也请用我的英语。