AngularJS:如何将新数据发布到现有JSON文件

时间:2015-12-16 14:48:55

标签: angularjs json forms post

我对Angular很新,所以如果我在这里遗漏了一些非常基本的东西,我很抱歉 - 这只是因为我已经搜索了一半的互联网,但我可以&似乎找到一个例子或解释来帮助我。

我有一个带有数据的JSON文件(news.json,本例存储在本例中):

[
    {
      "id": 1,
      "title": "Het allereerste nieuwsbericht",
      "body": "WE LOVE ANGULAR!!",
      "algemeen": true,
      "leerlingen": true,
      "personeel": true,
      "ouders": true,
      "day": "27",
      "month": "05"
    },
    {
      "id": 2,
      "title": "Het allertweede nieuwsbericht",
      (...)

应将新条目提交到JSON文件的表单的HTML模板:

<form ng-submit="submit()">
<label>Titel:&nbsp;&nbsp;&nbsp;</label>
<input type="text" ng-model="title" required /><br /><br />
<label>Tekst:<br /></label>
<textarea ng-model="body" required></textarea><br /><br />
<fieldset>
    <legend>Voor wie is dit nieuwsbericht bestemd?</legend>
    <input type="checkbox" ng-model="at_alg" value="Homepagina">&nbsp;&nbsp;Homepagina<br />
    <input type="checkbox" ng-model="at_lln" value="Leerlingen">&nbsp;&nbsp;Leerlingen<br />
    <input type="checkbox" ng-model="at_per" value="Personeel">&nbsp;&nbsp;Personeel<br />
    <input type="checkbox" ng-model="at_oud" value="Ouders">&nbsp;&nbsp;Ouders
</fieldset><br /><br />
<button type="submit">&nbsp;Sla het artikel op&nbsp;</button>

指令本身:

app.directive('postNews', function($http){
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'pages/postnews.html',
            link: function(scope, element, attrs) {
                $scope.submit = function() {
                    var toSend = {
                        title: $scope.title,
                        body: $scope.body,
                    }

                    $http.post('data/news.json', toSend)
                    .success(function(data, status, headers){
                        alert('Het bericht is toegevoegd.');
                        $scope.title = '';
                        $scope.body = '';
                    })
                    .error(function(data, status, headers){
                        alert('Oeps... er is iets fout gegaan. Probeer het later opnieuw.');
                    });
                };
            }
        };
 });

这根本不做任何事情。我究竟做错了什么?提前谢谢!

0 个答案:

没有答案