這是我的控制器(home.js
):AngularJS結合兩個變量在一起,沒有被告知這樣做
angular.module("HomeApp", ["BaseApp"])
.controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
var self = this;
self.posts = BaseService.posts;
BaseService.fetch.postsY(function() {
self.posts = BaseService.posts;
});
self.like = function(id, postType) {
BaseService.like(id, postType, function() {
console.log(self.posts);
});
};
}]);
這是BaseService(base.js
):
angular.module("BaseApp", [])
.factory("BaseService", ["$http", "$window", function($http, $window) {
var self = this;
self.posts = {};
self.cerrorMessages = [];
self.fetch = {
postsY: function(callback) {
$http.get('/postsY/')
.then(function(response) {
self.posts = response.data;
callback();
}, function(response) {
// Do something with the error.
});
}
};
self.like = function(id, postType, callback) {
$http.post("/" + postType + "/" + id + "/like/")
.then(function(response) {
angular.forEach(self.posts, function(post, index, obj) {
if (post.id == id) {
post.usersVoted.push('voted');
post.voted=true;
};
callback();
});
}, function(response) {
// Do something with the error.
});
};
return self;
}]);
當我加載home.html
(它加載home.js
),帖子加載成功(因爲在BaseService.fetch.postsY()
的回調中,我在self.posts = BaseService.posts
之後取回並更改BaseService.posts
。奇怪的是,after我喜歡一個帖子(它調用self.like
)self.posts
就會自動更新home.html
,即使沒有我在回調做self.posts = BaseService.posts
爲self.like
(當我在回調self.like
上home.html
登錄self.posts
,我可以看到post.voted=true
)。爲什麼AngularJS自動更新self.posts
在home.html
沒有我做self.posts = BaseService.posts
回調self.like
?
根據這個職位的答案被@AntonioLaguna:AngularJS updates variable in a different file without being instructed to do so
是監守我綁定self.posts
到BaseService.posts
當我做BaseService.fetch.postsY()
,但是,如果我改變BaseService.fetch.postsY()
這樣:
BaseService.fetch.postsY(function() {
// Do nothing in the callback.
});
那麼我的控制器上的self.posts
即使在獲取帖子後仍保持爲空(即使我在我的控制器上綁定了self.posts
之前的行爲:
self.posts = BaseService.posts;
隨着中說,如何來叫我self.like()
控制器上自動更新self.posts
即使調用BaseService.fetch.postsY()
一個空的回調函數不(考慮到我已經綁定self.posts
到BaseService.posts
在我的控制器的開始)?
嗯,有沒有什麼辦法可以在成功調用BaseService.fetch.postsY()後使AngularJS更新'BaseService.posts'(而不是通過執行self.posts = response.data來將它分配給一個新對象')? – user2719875
你可能嘗試初始化'self.posts'作爲數組'']'而不是對象'{}';除此之外,您可以嘗試遍歷'response.data'並將服務器對象推送到已建立的數組中,但如果您多次獲取相同數據,這會變得很奇怪...... – Claies
我嘗試初始化「self」。通過在我的BaseService中執行'self.posts = [];''作爲數組'''作爲數組',但是這並不能解決問題。而且,是的,我可以看到如何將服務器對象推入陣列可能會導致長期的問題。我想我會繼續在調用控制器函數的回調函數中執行self.posts = BaseService.posts;'在每次獲取帖子的服務器調用之後。謝謝您的幫助! – user2719875