set $Scope inside angular callback

Asked

Viewed 98 times

0

I’m trying to define a variable $scope.plan_id within a callback used in the $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 capacity $scope.save.

I’ve tried using the $apply() but the variable remains undefined.

  • The ideal would be to create a service to save the data, or a service with a method that returns a $Resource, for you to manipulate the return in the same scope of the controller. (I don’t know if I’m full of shit, but this is how I do it in our app)

1 answer

0

Good afternoon.

When a requisition is made be it $http or $resource in Angularjs in the function of callback the scope is different.

What I recommend is to store the scope in a variable before the execution of the $http or of $resource and that this variable is used within the callback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.