0

I'm using a promise. But when my promise resolves the binding to the view doesn't bind to the new value.

I made a small jsfiddle: http://jsfiddle.net/58q8khap/8/

Here's the view:

<div ng-controller="MyCtrl">
  Hello, {{name}}!
</div>

and the code:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope,ownservice) {
    $scope.name = "Noname";
    ownservice.getname().then(function(result){
        $scope.name = 'Superhero';
    });
}

myApp.service('ownservice', function ($q) {
    this.getname = function () {
        var deferred = $q.defer();
        setTimeout(function() {
                deferred.resolve('Superhero');
        } , 1000);
        return deferred.promise;
        }
});

2 Answers 2

2

Just replace the use of setTimeout by the angular version $timeout. That way angular will force a digest cycle and refresh your scope

Working fiddle : http://jsfiddle.net/cunuj46w/

Note that you should really use angular-powered versions of globals like $timeout or $window also for testing/mocking purposes

Sign up to request clarification or add additional context in comments.

2 Comments

Ah my problem is another one. And this was a simple sample. But due your answer I discovered that. Thanks
It's ok. I think it was a typo or something like that
1

after this line

 $scope.name = 'Superhero';

add

$scope.$apply();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.