【发布时间】:2017-12-10 16:10:38
【问题描述】:
我正在尝试使用服务在两个控制器之间共享数据。但是用 XHR 更改数据后,我没有看到数据更新。
angular
.module('appy', [])
.service('MyService', function($http){
return {
dataToChange: {
},
ajaxy: function(url){
var self = this;
setTimeout(function(){
console.log('now we are in the service!');
self.dataToChange = 'something new';
console.log(this.dataToChange);
}, 1000);
}
};
})
.controller('c1', ['$scope', 'MyService', function($scope, MyService){
$scope.myService = MyService;
$scope.ajaxy = function(){
$scope.myService.ajaxy();
};
}])
.directive('dirOne', function(){
return {
restrict: 'E',
templateUrl: 'dirone-temp.html'
};
})
.controller('c2', ['$scope', 'MyService', function($scope, MyService){
$scope.myData = MyService.dataToChange;
}])
.directive('dirTwo', function(){
return {
restrict: 'E',
templateUrl: 'dirtwo-temp.html'
};
});
但是当ajaxy 进行更新时,什么都没有发生。我尝试按照this question 的建议进行设置。没有喜悦。我还尝试添加手表。
$scope.$watch(function(){
return MyService.ajaxy();
}, function(oldVal, newVal){
$scope.somethingToChange = newVal;
console.log($scope.somethingToChange);
});
但仍然没有任何反应。这个物体也很大。我不想$watch它。
【问题讨论】:
-
首先仅供参考,在
setTimeout中,您的this指的是window。您需要将setTimeout回调绑定到您的对象(但是,这不会解决您的主要问题)。 -
好点。当我嘲笑这个时,我什至没有想到这一点。谢谢!
-
我建议使用根控制器,以便您可以获取该控制器中的数据并在 c1 和 c2 之间共享。
-
@sniels 为什么你认为这是最好的选择?您将如何设置“根控制器”?谢谢。
-
我并不是说这是最好的建议,但它在过去对我有用。我会试着举一个例子。
标签: javascript angularjs angularjs-directive xmlhttprequest