无法访问$ http.get方法中的控制器函数

时间:2016-11-23 11:17:45

标签: angularjs

这是我的控制者:

var app = angular.module('myApp', [ 'ngMaterial' ]);
app.controller('searchController',['$scope','$http',function($scope,$http) {
    this.selectedItemChange = function(item) {
        $http.get("url").then(function(response) {
            this.initializeProfiles();
        });
    }
    this.initializeProfiles = function() {}
}

但我收到错误TypeError: this.initializeProfiles is not a function

如何访问$ http.get的.then内的initializeProfiles()

2 个答案:

答案 0 :(得分:3)

您需要在回调内部引用控件,在执行对http.get的调用之前创建一个。

var app = angular.module('myApp', [ 'ngMaterial' ]);
app.controller('searchController',['$scope','$http',function($scope,$http) {
    this.selectedItemChange = function(item) {
    var me = this; // me = this
    $http.get("url")
        .then(function(response){
            me.initializeProfiles(); // me
    });
    }
    this.initializeProfiles = function() {}
}

有关如何在javascript:How does the "this" keyword in Javascript act within an object literal?中定义this的指南,请参阅此极好的答案。

答案 1 :(得分:0)

  var app = angular.module('myApp', [ 'ngMaterial' ]);
  app.controller('searchController',['$scope','$http',function($scope,$http) {
   var vm = this;
  vm.selectedItemChange = function(item) {
  $http.get("url")
    .then(function(response){
        vm.initializeProfiles();
   });
}
   vm.initializeProfiles = function() {}
}