角$范围不可用我的功能外 [英] Angular $scope not available outside my function

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

问题描述

有些新的角度和JavaScript。我有以下控制器写入使用工厂服务来访问本地JSON文件。其中大部分code是从的这个帖子丹Wahlin 。我无法访问的功能之外$ scope.books变量,想不通为什么。该函数中的执行console.log给我我找对象,但一外面返回undefined。我在做什么错在这里?谢谢你。

  app.controller('的FormController',['$范围,tocFactory',函数($范围,tocFactory){  $ scope.books;  getBooks();      功能getBooks(){
        tocFactory.getBooks()。
          成功(功能(数据,状态,头,配置){
            $ scope.books =数据;
            的console.log($ scope.books);
          })。
          错误(功能(数据,状态,头,配置){
            //记录错误
     })
  }
  的console.log($ scope.books);
  }]);


解决方案

由于您做一个Ajax,然后执行code的下一行。这并不意味着你必须保证您的Ajax响应准备在code的下一行的执行。

您总是可以得到成功的函数中它的响应值 $ HTTP 时,Ajax调用成功执行其被调用。

在这里<一读href=\"http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649\">How异步调用的作品?

Somewhat new to Angular and javascript. I have the following controller written use a factory service to access a local JSON file. Most of this code is derived (or completely taken) from this post by Dan Wahlin. I am unable to access the $scope.books variable outside of the function and cannot figure out why. The console.log inside the function gives me the object I am looking for, but the one outside returns undefined. What am I doing wrong here? Thanks.

app.controller('FormController', ['$scope', 'tocFactory', function ($scope, tocFactory) {

  $scope.books;

  getBooks();

      function getBooks() {
        tocFactory.getBooks().
          success(function(data, status, headers, config) {
            $scope.books = data;
            console.log($scope.books);
          }).
          error(function(data, status, headers, config) {
            // log error
     })
  }
  console.log($scope.books);
  }]);

解决方案

Because you are making an ajax and then executing the next line of code. Which doesn't mean you have guarantee that your ajax response is ready on execution of next line of code.

You could always gets its response value inside the success function of $http which gets called when ajax call executed successfully.

Read here How asynchronous call works?

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

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