Tream
Tream

Reputation: 1054

AngularJS: Data from service is not updated

I have a template, which gets data from a service. The data in the service are updated by a directive.

After the data gets updated, it won´t be updated in the template.

// In my template
{{service.get()}}

// In my service
.service('service', function($http){
    var _val = 5;

    return{
        get:function(){
            return val;
        },
        set:function(val){
            _val = val;
        }
    };
});

// In my directive
var someDirective = angular.module('app.someDirective',[]);

someDirective.directive('someDirective', ['service', function(service) {
    return function(scope, element, attrs){
        $(element).on('scroll', function(event){
            service.set(15);
        });
    };
}]);

If I call service.set(x) in any other place (like an other controller) it works 100% fine.

Maybe somebody knows, what I did wrong. (Thanks very much)

Edit To make it a bit more clear:

When the pages load, '5' is displayed (correctly). But when the value should be updated, the service.set()-function is called correctly (from the directive), but nothing changes in the template.

If I call service.set() anywere else, it works (value is updated in template).

Upvotes: 1

Views: 69

Answers (2)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

The quick fix is to wrap the set in a $timeout. The reason things don't get updated is because angular doesn't know to run a digest when $(element).on fires. Another way to fix this is with $evalAsync.

Upvotes: 1

dfsq
dfsq

Reputation: 193311

You event happens outside of the digest cycle. Simplest fix:

$timeout(function() {
    service.set(15);
});

Upvotes: 1

Related Questions