0

I am trying to update a service variable on resize. The update doesn't seem to be registered by the controller, even though I'm using angular.element to bind the event.

The initial setDevice() works, but on resize when I log the Device service on window resize from the controller there is no change to the service. I tried $rootScope.$apply to broadcast changes but this doesn't work either.

Service:

angular.module('health.device', [])
    .service('Device', function($window, $rootScope){

        var Device;

        function setDevice(dontApplyScope){
            Device = {
                isMobile: Modernizr.mq('only screen and (max-width: 40em)'),
                isTablet: Modernizr.mq('only screen and (min-width: 40.063em) and (max-width: 64em)')
            };

            if(!dontApplyScope){
                return $rootScope.$apply();
            }
        }

        setDevice(true);

        angular.element($window).bind('resize', setDevice);

        return Device;
    })

In the controller:

$scope.device = Device;

angular.element($window).bind('resize', function(){
    console.log(Device); // doesn't change
})
1
  • btw why not use existing libraries which does this... Commented May 5, 2015 at 5:17

1 Answer 1

1

Services work by being called once, and having the result provided whenever it is injected.

No matter how many times you inject Device, it will always be whatever the first function call returned.

If a window resize causes Device to change value, it will not change value when it is injected.

You could make it change value by getting whatever code depends on the service value to fetch it from a function instead, so that the internal state is separate from what is returned when it is first evaluated on first injection.

Another thing that is odd, why are you preventing $rootScope.$apply from being run everytime except the first execution?

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

1 Comment

Awesome, thanks for the clarification. I knew they got called once, but assumed the internal object was passed by reference, therefore updating. Will rework my code to accommodate this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.