gpt4 book ai didi

javascript - AngularJS 在没有被告知的情况下将两个变量绑定(bind)在一起

转载 作者:行者123 更新时间:2023-12-03 08:17:19 25 4
gpt4 key购买 nike

这是我的 Controller (home.js):

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 的回调中() 我在获取并更改 BaseService.posts 后执行 self.posts = BaseService.posts 。奇怪的是,在我喜欢一个帖子之后(调用self.like),self.posts 会自动在 home.html 上更新,即使我没有执行 self.posts = BaseService。 postsself.like 的回调中(当我在 home.html 的回调中记录 self.posts 时>self.like,我可以看到post.voted=true)。为什么AngularJS会自动更新home.html<中的self.posts/code> 没有我在 self.like 回调中执行 self.posts = BaseService.posts

根据@AntonioLaguna在这篇文章中的回答:AngularJS updates variable in a different file without being instructed to do so

这是因为当我执行BaseService.fetch.postsY()时,我将self.posts绑定(bind)到BaseService.posts,但是,如果我将 BaseService.fetch.postsY() 更改为:

        BaseService.fetch.postsY(function() {
// Do nothing in the callback.
});

然后,即使在获取帖子后,我的 Controller 上的 self.posts 仍然为空(即使我之前通过执行以下操作在我的 Controller 上绑定(bind)了 self.posts :

self.posts = BaseService.posts;

话虽如此,为什么调用 self.like() 自动更新我的 Controller 上的 self.posts 即使调用 BaseService.fetch.postsY()带有空回调函数的 则不会(考虑到我已经在 Controller 的开头将 self.posts 绑定(bind)到 BaseService.posts)?

最佳答案

对于BaseService.posts,您首先将其分配给一个空对象,然后将其分配给一个完全不同的对象(response.data),这在 postsY 函数中可能是一个数组。 Controller 仍将拥有对空对象的引用,并且不知道该对象已被带有数组的服务替换。

self.like() 而言,该函数只是迭代现有的 posts 数组并修改其属性对象。如果 Controller 正确指向对象数组,由于数组本身没有被删除和替换, Controller 将指向内存中数组中所有对象的同一个实例,并且对这些对象属性的更改将得到反射(reflect)。

关于javascript - AngularJS 在没有被告知的情况下将两个变量绑定(bind)在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com