gpt4 book ai didi

json - Angularjs - 更新 JSON

转载 作者:行者123 更新时间:2023-12-01 02:27:18 26 4
gpt4 key购买 nike

我对 Angularjs 很陌生,并且在弄清楚如何更新我从 JSON 创建的 $scope 元素时遇到了问题。基本上我有一个包含获取 JSON 的函数的服务:

app.service('JSONService', function($http){         
return{
getJSON: function(){
return $http.get('posts.json')
.then(function(response){
return response.data;
});
}
};
});

然后我有一个 Controller ,其中包含一个函数,该函数在单击按钮时获取 JSON 数据并将其放入 $scope.data 和我想用来更新 $scope.data 的第二个函数:
app.controller('PostController', function PostController($scope, JSONService){
$scope.data;

$scope.getJSON = function(){
$scope.data = JSONService.getJSON();
};
$scope.addPost = function(){
// Add to $scope.data
};
});

目前,我成功地获取了 JSON 数据,并能够使用它来填充我的 View 的各个方面,但我被困在如何继续更新 $scope.data 以便:
  • 它实际上更新了
  • 更新反射(reflect)在我的 View 中

  • 我试过 $broadcast、$scope.data.push、$scope.data.posts.push。这些要么完全不起作用,要么出现错误。我敢肯定这可能是一个简单的答案,但我觉得我可能对 Angularjs 和 JSON 缺乏经验来了解它。提前致谢。

    最佳答案

    所以我认为上面的代码有几个问题。希望这可以帮助您理顺它:

    $http.get() 函数返回一个“ promise ”。 Promise 有一个 then() 函数,您正在使用它,但您可能应该调整以获取返回的数据并将其直接放入 $scope。由于请求是异步的,因此在您的服务中的 then() 中执行“return”语句实际上并没有什么可去的地方。 Angular 知道如何使用 Promise,因此您可以绑定(bind)到 UI 中的数据,但实际上您不会直接在 $scope.data 下找到数据。 $scope.data 仍然是一个 Promise 对象,并且数据将在另一个属性中(类似于 $scope.data.promiseData ——虽然不记得确切的属性是什么)。你可以这样调整:

    app.service('JSONService', function($http){         
    return {
    getJSON: function() {
    return $http.get('posts.json');
    }
    };
    })

    Controller :
    app.controller('PostController', function PostController($scope, JSONService){
    $scope.data;

    $scope.getJSON = function(){
    JSONService.getJSON()
    .then(function (response) {
    $scope.data = response.data;
    });
    };
    $scope.addPost = function(postText){
    // Add to $scope.data (assuming it's an array of objects)
    $scope.data.push({postText: postText});
    };
    });

    HTML:
    <div data-ng-repeat="post in data">{{post.postText}}</div>

    <input type="text" ng-model="newPostText">
    <button type="button" ng-click="addPost(newPostText)">Add Post</button>

    关于json - Angularjs - 更新 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15369726/

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