pop_up
pop_up

Reputation: 1579

view not refreshing after promise is finished

i am using angular 1.

i am using a variable "isWorking" to display a loader.

I call a promise, but when the promise is finished, the spinner is loading even if i set "isWorking" to false.

My controller :

/** @ngInject */
export default function (
MyFactory
) {
    var ctrl = this;
    ctrl.isworking = false;


    ctrl.submit = function () {
        ctrl.isworking = true;

        MyFactory.callCreate({}, {liste: ctrl.args}).$promise.then(function (response) {
            ctrl.isWorking = false;
            console.log(ctrl.isWorking);
        }, function (error) {
            ctrl.isWorking = false;
            console.log(ctrl.isWorking);
        });

    };
}

Extract of my view :

<button type="submit" class="button"
        ng-disabled="myCtrl.isworking"
        ng-click="myCtrl.submit()">
    <i ng-show="myCtrl.isworking" class="fa fa-spinner"></i> submit
</button>

how can i do it correctly ?

thanks

Upvotes: 0

Views: 33

Answers (2)

georgeawg
georgeawg

Reputation: 48968

One possibility is that the promise is not integrated with the AngularJS framework. Try converting it to an AngularJS promise:

/** @ngInject */
export default function (
MyFactory, $q
) {
    var ctrl = this;
    ctrl.isworking = false;


    ctrl.submit = function () {
        ctrl.isworking = true;

        var promise = MyFactory.callCreate({}, {liste: ctrl.args}).$promise;
        var angularPromise = $q.when(promise);
        angularPromise.then(function (response) {
            ctrl.isWorking = false;
            console.log(ctrl.isWorking);
        }, function (error) {
            ctrl.isWorking = false;
            console.log(ctrl.isWorking);
        });    
    };
}

The $q.when method wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

For more information, see

Upvotes: 0

iwonz
iwonz

Reputation: 421

Working example is here: https://stackblitz.com/edit/stackoverflow-answer-58730526. It's problem of asynchronous. You can use $scope.$evalAsync(() => { /* Your changes of bindings */ }); or just call $scope.$digest(); after your changes of bindings. But be careful with $digest already in progress error in this case.

Upvotes: 1

Related Questions