【问题标题】:How to update model using angularjs, Django,Django rest framework如何使用 angularjs、Django、Django rest 框架更新模型
【发布时间】:2015-01-28 13:30:40
【问题描述】:

我通过它的 id 有这样一个帖子的 json 表示:

http://127.0.0.1:8000/update/1?format=json
{"title": "about me", "content": "I like program", "created":    "2014-11-29T18:07:18.173Z",   "rating": 1, "id": 1}

我尝试通过点击按钮来更新评分:

 <button ng-click="click(post.id)">Click me</button>

我有这样的javascript代码:

<script>
var demoApp = angular.module('demoApp',['ngResource']);
    demoApp.controller( 'AllPosts', function ($scope, $http)
    {
    $http.get('/blogpost/?format=json').success(function(data,status,headers,config)
    {
    $scope.posts = data.results; 
    $scope.predicate = '-title';

      $scope.click = function(post_id, $resource){
       var Post = $resource('/update/:PostId ',{PostId:post_id,format:'json'} );  
       post = Post.get({PostId:post_id}, function() {
       post.rating = post.rating+ 1 ;
       post.$save();
       });
       };

 }).error(function(data,status,headers,config)
     {} )
    ;})

 </script>

Peharps 我错了,因为在 json 中我只有一个对象。但我真的不知道

此外,我有这样的观点,即通过某个帖子的 id 获得一个 json:

class UpdateModel(generics.RetrieveUpdateDestroyAPIView):
      lookup_field = 'id'
      queryset = BlogPost.objects.all()
      serializer_class = BlogPostSerializer
      permission_classes = (AllowAny,)

【问题讨论】:

    标签: javascript python json django angularjs


    【解决方案1】:

    快速整理您的script 标记表明,如果http 调用成功,您只定义函数click

    我建议将 click 方法的定义移到成功回调之外。

    在单击实际按钮之前,您还可能遇到了单击函数尚未定义的竞争条件。无论如何,您都希望将该函数定义移动到实际创建控制器的位置。

    建议的修改(将 click 定义移到 http 调用响应之外):

    var demoApp = angular.module('demoApp', ['ngResource']);
    demoApp.controller('AllPosts', function($scope, $http, $resource) {
        $scope.click = function(post_id) {
            var Post = $resource('/update/:PostId ', {
                PostId: post_id,
                salutation: 'json'
            });
            post = Post.get({
                PostId: post_id
            }, function() {
                post.rating = post.rating + 1;
                post.$save();
            });
        };
    
        $http.get('/blogpost/?format=json').success(function(data, status, headers, config) {
            $scope.posts = data.results;
            $scope.predicate = '-title';
        }).error(function(data, status, headers, config) {});
    })
    

    更新:

    • 将 $resource 注入到控制器中
    • 从点击函数参数中删除了 $resource

    【讨论】:

    • 我从成功回调中删除了点击功能,但没有
    • 我更新了我的答案,以向您展示我在说什么,而不仅仅是展示您的格式化代码。
    • 我再次更新,请参阅答案中的更新部分。话虽如此,我对 ngResource 并不熟悉,我会考虑将其中的一些逻辑重构为服务或工厂。
    • 我在尝试,但没有帮助
    • 如果您将浏览器控制台的输出复制到哪里会有所帮助。那里可能有一些角度错误消息。
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    相关资源
    最近更新 更多