문제

Here's the situation: I have a service that uses LocalStorage to save some Objects when I click some buttons.

These LocalStorage Objects are connected to my Header $scope. The problem is that I only load the header (and its $scope) when I load the first page and then it reamins stucked, 'cause there is no need to load it every time I change the page. But, actually, I need the header to "reload" its $scope when I'm done with saving things in LocalStorage, because in it I have a badge that has to show the updated length of LocalStorage elements (it's a Cart badge, to be clear).

So, is there a way to refresh a specific controller $scope from a Service or from another Controller? Maybe with some $scope.$apply() thing? Or there is a way to bind the LocalStorage element in the Header controller in order to do something when it has changed?

PS: No, I can't move out the Cart badge from the header and Yes, I really have to use LocalStorage (it's a specific request).

도움이 되었습니까?

해결책

You need to message between your scopes, as angular scopes use prototype inheritance. In short if you have a parent scope with a property "foo", and you update "foo" in a child scope, the child scope gets a "new copy" of "foo".

To achieve what you want one can use $scope.$emit() to send an event updates through the scope hierarchy and $scope.$on() to receive events. Something like this.

function ParentController($scope, ...) {

     $scope.numberOfThings = 5;

     // Process 'updateThings' event 
     $scope.$on('updateThings', function(value) { 
         $scope.numberOfThings = value; 
     }); 
}

...

function ChildController($scope, ...) {

     $scope.someCallback = function() {

          // Send 'updateThings' up the scope chain. 
          $scope.$emit('updateThings', 47); 
     }
}  

If you want to do this the other way around, one can push events downward through the scope chain, one can use $scope.$broadcast().

다른 팁

'Refreshing' the controller is usually done not directly by using data in $rootScope, but by creating and emitting custom events with $emit method

You can emit your own event through the $rootScope and it will then be propagated to all child scopes, where you can listen on that event

////// controller or service or directive

$rootScope.$emit('myOwnEvent', dataObj);

////// another controller

$scope.$on('myOwnEvent', function(newData) {
    $scope.data = newData; // or whatever
});

you can use $rootScope instead of $scope in Header and you can update $rootScope value from another controller.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top