gpt4 book ai didi

javascript - 何时解决注入(inject) Controller 的服务的双向绑定(bind)问题?

转载 作者:行者123 更新时间:2023-11-30 17:07:02 26 4
gpt4 key购买 nike

我试图理解为什么下面的代码只会记录

Array []
Array [object, object]

当我按预期提交表单时

Array [object, object]
Array [object, object]

https://gist.github.com/anonymous/b5a9dd7634ee97bc01cf

不应该

$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});

立即更新服务?

如有任何建议,将不胜感激

angular.module('flapperNews', [])
.factory('postsFactory', [function(){
// Modularize posts frontend storage for better mock testing and independency of scope
var posts_factory_object = {
posts_list: []
};
return posts_factory_object;
}])
.controller('MainCtrl', [
'$scope',
'postsFactory',
function($scope, postsFactory){

// Bind scope.posts to postsFactory.posts_list
$scope.posts = postsFactory.posts_list;

// Variable pseudo post data for test
$scope.posts = [
{title: 'post 1', upvotes: 5},

];

// Frontend function for keeping track of state purely in frontend
$scope.addPost = function(){
// Check if inputted string is undefinied or empty
if (!$scope.title || $scope.title ===''){ return; }

$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
$scope.title = '';
$scope.link = '';

console.log(postsFactory.posts_list);
console.log($scope.posts);
};


}]);

最佳答案

您的服务没有得到更新,因为您正在用另一个数组覆盖 $scope.posts 持有的服务对象 postsFactory.posts_list 的引用,方法是:

 $scope.posts = [
{title: 'post 1', upvotes: 5},
];

因此,对 $scope.posts 所做的任何更改都不会反射(reflect)在服务中的对象中,因为它们都指向不同的引用。您可以通过执行以下操作来验证:-

 $scope.posts.push({title: 'post 1', upvotes: 5});

只要两个属性都持有相同的引用,您就可以看到两边反射(reflect)的变化。

关于javascript - 何时解决注入(inject) Controller 的服务的双向绑定(bind)问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791209/

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