Angular中的Javascript调用函数

时间:2014-03-04 08:50:05

标签: javascript angularjs

我在Angular应用程序中遇到了一个奇怪的问题所以我问了一些简单的Javascript问题,以便清楚地了解基础知识(请参阅Javascript Callbacks)。该解决方案适用于纯Javascript,但当应用于我的Angular应用程序时,问题仍然存在。

我已经定义了一个创建对象新实例的服务。

appModule.factory('myService', ["$rootScope", "$http", "DataCall", "$routeParams", "$log", function($rootScope, $http, DataCall, $routeParams, $log ) {

/////////////////////////// My- Object /////////////////////////////////////
MyObject= function(a, b, callback) { 
  var thisTemp = this;
  this.accounts = [];
  thisTemp.accounts[0] = 1;
  thisTemp.accounts[1] = 2;
  DataCall.get('xxx',function(data, status){                 
    callback.call(this);
    });
  } 
});

在我的控制器中,我创建了新对象并将其分配给范围变量

within controller....
$scope.pageInit = function () {
  $scope.currentObject = {};
  $scope.currentObject = new myService.MyObject('a', 'b', function(){

     alert(this.account[0]);
  });

这仍然不起作用。在回调函数中,'this'指的是'window'而不是currentObject。

任何帮助都将受到高度赞赏。

3 个答案:

答案 0 :(得分:0)

MyObject= function(a, b, callback) { 
  var thisTemp = this;
  this.accounts = [];
  tmpThis.accounts[0] = 1;
  tmpThis.accounts[1] = 2;
  DataCall.get('xxx',function(data, status){
    // it is here 'this' become 'window'    
    callback.call(this);
    });
  } 
});

既然你愿意阅读javascript如何回调,我就让你弄明白了。

答案 1 :(得分:0)

在你的MyObject中,你得到了对'this'的引用(引用了MyObject函数)并且你把它称为thisTemp。由于您在变量中保留了该引用,因此除非您想引用另一个上下文,否则应该使用该变量而不是“this”。

appModule.factory('myService', ["$rootScope", "$http", "DataCall", "$routeParams", "$log", function($rootScope, $http, DataCall, $routeParams, $log ) {

  /////////////////////////// My- Object /////////////////////////////////////
  function MyObject(a, b, callback) { 
    var thisTemp = this;
    this.accounts = [];
    thisTemp.accounts[0] = 1;
    thisTemp.accounts[1] = 2;
    DataCall.get('xxx',function(data, status){                 
      callback.call(thisTemp);
    });
  }

  return {
    MyObject: MyObject
  }
}]);
控制器内的

....

$scope.pageInit = function () {
  $scope.currentObject = {};
  $scope.currentObject = new myService.MyObject('a', 'b', function(data){

     alert(data.account[0]);
  });

答案 2 :(得分:0)

无需在控制器中显式实例化您的服务。 Angular会在需要时为您完成此操作。

所以你可以把你的服务重新写成这样的东西。

appModule.factory('myService', ["$rootScope", "$http", "DataCall", "$routeParams", "$log", function($rootScope, $http, DataCall, $routeParams, $log ) {

  /////////////////////////// My- Object /////////////////////////////////////

    myService = {
      accounts : [],
      accounts[0] : 1,
      accounts[1] : 2,

      dataCall : function(a, b, callback) {
        callback.call(this);
      }
    }

    return myService;
});

within controller....
$scope.pageInit = function () {
  $scope.myService = myService;
  $scope.myService.currentObject = myService.dataCall('a', 'b', function(){

     alert($scope.myService.accounts[0]);
  });