传递给闭包的Angular参数未定义

时间:2014-09-28 15:50:49

标签: javascript ajax angularjs

所以我有这样的观点:

$scope.getStructs = function(path, save_to) {
    $http({method: 'GET', url: 'http://localhost:8001/www-root/' + path}).

         success(function(data, status, headers, config) {
             console.log("Success:  " + data);
             save_to = data;
         }).

         error(function(data, status, headers, config) {
             alert("Error: " + status);
         });
    });

当我像这样调用函数时:

$scope.getStructs("get_users.pl", $scope.users);

该函数正确地从服务器获取数据,但$scope.users变量未定义。问题是 - 为什么?

2 个答案:

答案 0 :(得分:0)

不是传递变量,只需返回承诺并按次调用处理:

$scope.getStructs = function (path) {
 return $http({
     method: 'GET',
     url: 'http://localhost:8001/www-root/' + path
 });
}

$scope.getStructs("get_users.pl").
 success(function (data, status, headers, config) {
     console.log("Success:  " + data);
     $scope.users = data;
 }).
 error(function (data, status, headers, config) {
     alert("Error: " + status);
 });

编辑:

看起来你想要重复使用它,所以它应该是一个可以注入任何控制器的工厂。像这样:

(function() {
  function StructFactory($http) {
    return {
      get: function(path) {
        return $http.get(path);
    }
  }
  angular.module('MyFactories', [])
         .factory('StructFactory', StructFactory);
})();

在您的应用模块中加入模块:

app = angular.module('myApp', ['MyFactories']);

然后在您的控制器中包含工厂:

(function() {
  function MyController($scope, StructFactory) {
    $scope.getStructs = function() {
      StructFactory.get('get_users.pl')
        .success(function(data) {
          $scope.users = data;
        })
        .error(function(data) {
          console.log('Error: ' + data);
        });
  }
  app.controller('MyController', MyController);
})();

现在,您可以轻松地在所有控制器中重复使用工厂。您只需向工厂添加更多方法(添加,删除等)即可。

答案 1 :(得分:0)

因为参数只是变量的副本。

var a = 10;
function b(arg){
  arg--;
  console.log(arg);
}
// it will create a temp variable same as `a`, and execute `temp--; console.log(temp)`
b(a); //9
// real `a` not change
console.log(a); //10
相关问题