javascript - 使用工厂函数的 AngularJS Controller

标签 javascript angularjs

我有以下代码,其中 Controller 使用factory函数通过API请求获取用户数据。

Controller

myApp.controller('UserApiCtrl', function($scope,$auth,Account){

    $scope.getProfile = function(){
        Account.getProfile()
            .then(function(response){

                $scope.user = response.data;

            })

            .catch(function(response){
                // errors handled here
            })
    };

    $scope.getProfile();

})

工厂

angular.module('MyApp')
    .factory('Account', function($http){
        return {
            getProfile: function(){
                return $http.get('/api/me');
            }
        }
    });

现在在 Controller 中,当我 console.log(response.data) 时,json 数据可用,但是当我 console.log($scope.getProfile())它是未定义的。

谢谢!!

最佳答案

这是答案,请阅读以下要点以理解这个概念。

  1. 您正在为作用域变量 $scope.user 赋值,因此您可以为其进行日志记录。
  2. 您已成功收到回复,因此您也可以再次登录此处。

但是当您尝试记录 console.log($scope.getProfile()) 时,它不会返回任何内容。在 Angular 中,您可以将所有内容保留在范围对象中。

关于javascript - 使用工厂函数的 AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740084/

相关文章:

javascript - 如何检查它是字符串还是json

node.js - XMLHttpRequest 无法加载 http ://127. 0.0.1 :1337/. 请求的资源上不存在 'Access-Control-Allow-Origin' header

angularjs - 涉及 ng-show 的 Protractor 测试

php - 使用 getElementByClassName,并通过表单携带变量

用于验证 URL 的 Javascript 代码在 IE 和 Chrome 中有效,但在 Firefox 中无效

javascript - Grails - 在javascript更改后重新部署

javascript - 如何在 if 语句中仅追加一个项目一次?

javascript - 如何在angularjs中使用表达式绑定(bind)属性名称?

javascript - Laravel 5 和 AngularJS 从 url 中删除 '#'

javascript - 使用 ng-repeat 加载图像