我有一个 Angular 应用 myApp
有服务myService
,拿着一个物体data
由两个 Controller 使用,parentCtrl
和 childCtrl
后者继承前者:https://jsfiddle.net/OleWahn/7ehLva10/2/
我引用了 data
在 parentCtrl
内通过 $scope.data = myService.getData()
这也使得它可以从 childCtrl
访问.
我定义 data
在关闭myService
,因此 $scope.data
只是对 data
的引用.
因此,我可以更改 data
子 Controller 和每个人中的属性,myService
, parentCrl
和 childCtrl
将意识到这些变化。到目前为止,还不错。
我的问题如下:如果我想覆盖整个 data
我调用的对象 myService
方法 setData
在 childCtrl
内.
再次,我希望每个人都能收到 data
的通知。已经改变。
$scope.data
然而仍然指向最初定义的对象,不会被myService
通知那data
已经改变,这将是我的最后一个问题:
有没有办法自动更新对服务中定义的对象的范围引用?
最佳答案
使用angular.copy
的目标参数
angular.copy1
Usage
angular.copy(source, [destination]);
- If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
因此,与其替换范围引用,不如保留引用、清空它并用新内容填充它。
function setData(newData) {
//DO this
angular.copy(newData, data);
//Instead of this
//data = newData;
}
关于javascript - Angular : Automatically update a scope reference to an object defined in a service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750045/