angularjs资源不返回正确的值

时间:2013-06-11 23:56:12

标签: javascript angularjs

我的控制器在angularjs中有这个代码

    $scope.likeit = function(entry) {
        entry.like = !entry.like;
        var ret = VoteResource.save(entry);
        console.log("Return Object")
        console.log(ret)
        console.log("======================================")
        console.log("Return Like Property")
        console.log(ret.like_count)
        return ret
    };

当我尝试在我的视图中触发此功能并在控制台中检查时,这是输出

    Return Object 
       Resource {comment_count: 0, confess: "Hello world!!! kk", created_at: "2013-06-11T00:26:25Z", feeling_id: 0, hug_count: 0…} 
       comment_count: 0
       confess: "Hello world!!! kk"
       created_at: "2013-06-11T00:26:25Z"
       feeling_id: 0
       hug_count: 0
       id: 1
       like_count: 0
       metoo_count: 0
       updated_at: "2013-06-11T23:48:16Z"
       user_id: null
       __proto__: Resource

       ====================================== 
       Return Like Property 
         1 

我的问题为什么它是ret.like_count返回1.在第一个控制台日志中,like_count的资源值为零(0)但是在ret.like_count输出中它返回1.为什么?那么如何在资源中访问like_count呢?

1 个答案:

答案 0 :(得分:0)

好的,我发现了问题。资源是异步的所以我使用$ q(promise)注入这是解决问题的部分代码和一些链接$resource in angularjs does not work properly

    save: function(confession) {
        var defferred = $q.defer()
        resource.save(confession,

            function(response) {
                console.log(response);
                confession.like_count =  response.like_count
                defferred.resolve(response);
            },
            function(response) { defferred.reject(response)}

        );

    }