2014-11-11 1 views
4

"this"변수 안에 저장해야하는 then() 내에서 일부 데이터가 반환됩니다. 범위 내에 저장되지 않고 콜백 내부에 래핑되었으므로 컨트롤러의 "this"가 유효하지 않습니다. 데이터를 다시 버블 링하여 "this"안에 저장할 수 있습니까? 아래를 참조AngularJS에서 "컨트롤러로"구문과 "this"를 사용하는 경우 약속의 콜백에서 "this"를 참조하는 방법은 무엇입니까?

angular.module('logisticsApp.controllers'). 
controller('InventoryCtrl', ['$scope', '$http', '$window', 'DataService', 
    function ($scope, $http, $window, DataService) { 

    this.inventory = ''; // need to have data stored here 

    $scope.$on('$viewContentLoaded', angular.bind(this, function() { 
     // "this" is still valid here 
     myService.getInventory().then(function(data) { 
     // "this" is no longer valid! 
     $scope.inventory = data; // so this fails 
     }); 
    })); 
}]); 
+0

[함수 내부의 별칭 컨트롤러에 변수를 할당하는 방법?] (HTTP의 가능한 중복 : //stackoverflow.com/questions/26822784/how-to-assign-variables-to-an-aliased-controller-inside-a-function) – zeroflagL

답변

9

당신은 angular.bind를 사용할 수 있습니다

myService.getInventory().then(angular.bind(this, function(data) { 
    console.log(this.inventory); 
})); 

angular.bind docs에서 :

자체에 바인딩 기능 (FN)를 호출하는 함수를 돌려줍니다 (자기는 FN이된다).


또한과 같이 컨텍스트 (이)에 대한 참조를 저장할 수 있습니다

var self = this; 

myService.getInventory().then(function(data) { 
    console.log(self.inventory); 
}); 
+0

'var self = this;'접근법은 정말 고맙습니다! – alexkb

관련 문제