2016-11-23 33 views
1

內訪問控制器功能這是我的控制器:

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

您需要從回調中引用控件,在執行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() {} 
} 

看到這個外觀極好SO回答指導this是如何在JavaScript中定義:How does the "this" keyword in Javascript act within an object literal?

+0

This Works!謝謝。 但爲什麼會發生這種情況? – pkyo

+0

@pkyo - 它與'this'有關,引用會根據調用堆棧而變化,並且不會在回調中隱式捕獲。有一個很好的答案解釋了這個'this'的所有細節,給我一分鐘,我會找到它。 – Igor

+0

@pkyo - 發現它,我更新了我的答案,並在最後包含它。 – Igor

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() {} 
}