javascript - AngularJS 从 Controller 外部的 AJAX 获取返回值

标签 javascript jquery ajax angularjs

好的,所以我有一个带有执行 HTTP 请求的函数的服务,并且返回的值设置为 $scope,但是这不起作用,因为看起来 $scope 不等待 AJAX 调用。我如何从 Controller 外部的服务函数返回 AJAX 结果?

示例:

//Controller
app.controller('Controller', function($scope, $http, Service){

    // $scope WILL NOT BE SET TO THE VALUE RETURNED, the returned value is UNDEFINED
    $scope = Service.getData();

}


// Get server data from service function
app.service('Service', function ($http){

    this.getData = function(){
        //Get server data

       return { data: result }
    }
}

最佳答案

尝试将服务调用放入解析函数中并将结果注入(inject)到 Controller 中。

这篇博文有一个很好的例子:http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

关于javascript - AngularJS 从 Controller 外部的 AJAX 获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443472/

相关文章:

javascript - 如何使用 Soundcloud API 下载轨道?

javascript - 通过 jQuery 和 FormData 的 Ajax POST 请求 - $_POST 在 PHP 上为空

mysql - Ajax 响应未在 View 页面中加载

javascript - ng-if 花费 500 个观察者 - 性能

javascript - 在javascript中调用函数后,我无法为变量赋值

javascript - 如何用另一个 div 隐藏动画 div

Jquery 在打开新的 div 之前隐藏打开的 div

javascript - 默认选中按钮

javascript - 传递参数日期时间?在 mvc 和 jquery 中

jquery - 在 Codeigniter 上使用 jQuery AJAX 在 jQuery 选项卡中加载一段 html