2016-11-23 2 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

これは機能します。ありがとう。 しかし、なぜこれが起こりますか? – pkyo

+0

@pkyo - これは 'this'と関係があり、コールスタックによって参照が変わり、コールバックで暗黙に捕捉されません。 「this」の詳細をすべて説明してくれたとても良いSO答えがあります。私には分かります。私はそれを見つけるでしょう。 – 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() {} 
} 
関連する問題