set $ scope within angular callback

0

I'm trying to define a $scope.plan_id variable within a callback used in $http , and always when I check this variable I get undefined .

$http({
    method: 'get',
    url: '/api/pricings/get'
}).then(function (response) {
    $scope.proposals.plans = [];
    response.data.forEach(function (plan) {
        $scope.proposals.plans.push({title: plan.description, id: plan.id});
    });
    $('.ui.search.plans').toggleClass('loading');
    $('.ui.search.plans').search({
        source: $scope.proposals.plans,
        onSelect: function (response) {
            $scope.plan_id = response.id; // definição de $scope.plan_id
        }
    });
}, function (response) {
        messageService.alertDanger('Ocorreu um erro ao exibir as propostas. Refaça o login e tente novamente.');
});

This method is within a function $scope.show , and I'm trying to access $scope.plan_id in another function $scope.save .

I've tried to use $apply() but the variable is still undefined .

    
asked by anonymous 27.11.2017 / 19:31

1 answer

0

Good afternoon.

When a request is made be it $http or $resource in AngularJS in the callback function the scope is different.

What I recommend is that the scope be stored in a variable before the execution of $http or $resource and that this variable be used inside callback     

30.11.2017 / 20:55