为什么我无法访问在较高范围内创建的变量

时间:2015-06-26 20:13:44

标签: javascript jquery angularjs

我出于某种原因挣扎着这个js代码。我无法访问ajax函数中的变量。 我尝试通过放置"格式化的"来解决这个问题。变量高于ajax函数但我无法从内部访问它。我该如何解决这个问题?

angular.module('ireg')
.controller("compoundSearchController", function(){
    var vm = this;
    vm.searchText = "Enter your search here...";
    vm.compounds = getJSON();

    function getJSON(){
        var formatted = "initial";  

        console.log(formatted); // equals initial

        $.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
            formatted = jQuery.parseJSON( result );
            console.log(formatted); //equals the correct object
        }})

        console.log(formatted); // equals initial
        return formatted;
    }

    console.log(vm.compounds); // equals initial

});

2 个答案:

答案 0 :(得分:1)

AJAX调用的异步行为是实际行为与预期行为之间差异的原因。

将您的代码更新为

var formatted = "initial";  

$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
    formatted = jQuery.parseJSON( result );
    vm.compounds = formatted;
}})

答案 1 :(得分:0)

你无法得到ajax调用在success之外的响应,因为它们本质上是asynchronous。您需要使用他们的回调来获取success,或者您也可以使用.then函数,当ajax调用得到解决时,它会调用。

注意

  

不要将jQuery ajax与AngularJS混合使用digest   循环,你需要手动强制它,用$http

替换ajax

<强>更新

以下是角度版本$.ajax

    $http.get("http://localhost:8080/ireg/app/php/returnAllCompounds.php")
    .success(function(result){
        formatted = jQuery.parseJSON( result );
        console.log(formatted); //equals the correct object
    }});