角JS $范围不持有的JSON值 [英] angular js $scope not holding json values

查看:109
本文介绍了角JS $范围不持有的JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角是失去我的我的JSON值,我试图找出原因。我想我需要做出一个承诺或超时,或者适用。我不太清楚...

Angular is loosing my my JSON values, and i'm trying to find out why. I think I need to make a promise or a time out, or maybe apply. I'm not quite sure...

角版本:1.2.1

 galleryApp.controller('GalleryCtrl', function ($scope, $http, $routeParams, $filter){
    $http.get('mygallery.json').success(function(data) {

        $scope.gallery = data;

        //DISPLAY: CONTENTS OF JSON IN OBJECT : WORKS 
        console.log($scope.gallery);
    });

    //DISPLAY: undefined : DOES NOT WORK AS EXPECTED
    console.log($scope.gallery);

    //DISPLAY: CONTENTS OF OBJECT: I can see scope.gallery exists!
    //I just can't seem to access scope.gallery directly outside of http.get()
    console.log($scope);

  });

请注意:scope.gallery或​​画廊工作完全正常,我的看法! {{gallery.name}}等。

Note: scope.gallery or "gallery" works perfectly fine in my view! {{gallery.name}} etc.

好像有一些幕后的东西的角度这样做是对的范围,或者一些概念,我不是很抓。

It seems like there is some behind the scenes things angular is doing to the scope, or some concept that i'm not quite grasping.

推荐答案

嗯,这是微不足道的$ http.get是一种异步操作。因此,尽管这是工作的code的其余部分将完成。如果你登录了$ scope.gallery它是不确定的呢。如果你登录了$范围内它仍然是不确定的,但调用成功回调时将被更新。为你这种效果的原因钍只是执行console.log的功能,它不是在写当前快照,但对象本身,所以如果修改控制台的输出将分别更新。但是,在你的code一般没有的$ http.get外面你在这里会正常运行。所以,你应该要么使用成功回调或使用$手表跟踪更改。

Well, it's trivial as $http.get is an asynchronous operation. So while it is working the rest of the code will be finished. If you log the $scope.gallery it is undefined yet. If you log the $scope it's still undefined but will be updated when the success callback is invoked. Th reason of this effect for you is just feature of console.log which writes not the current snapshot but the object itself so if changed the output of the console will be updated respectively. But in general none of your code outside of the $http.get will work as you expected here. So you should either use the success callback or use $watch to track the changes.

也可参考此文档: $ HTTP ,的 $ q

Also refer to this documentation: $http, $q

这篇关于角JS $范围不持有的JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆