Skip to content Skip to sidebar Skip to footer

Stop Angularjs From Creating New Controller/$scope Cache And Use Cached One

Using $routeProvider every time user clicks on a link, a new $scope is being generated. That means all the data is lost. How can i make Angular use the same controller/$scope? Expl

Solution 1:

In AngularJS, $scope is not meant to hold data that persists across your application. For that, you want to use a service that is injected into both controllers. If you provide more detail on what data you're missing across routes, I would be happy to revise this answer to include something a little more actionable.

In re your PS: You can inject the $route service to get information about the current route; the $route.current.controller property will give you the constructor function of the current route.

Solution 2:

For those researching how to "unbind" in AngularJS, he is a bit of info (related to the OP's last comment above)

When a view is destroyed, it's basically marked for garbage collection - but it's still there. That is why you are getting multiple requests when a scroll happens - because it's still listening for events.

So the easiest way to deal with this (that I have found, though I'd like to learn of other ways) is to listen for the $destroy event and react on it.

You can "unbind/unlisten" for an event by keeping a reference to what is returned by the $on method. Here is an example taken from a controller:

$scope.systemListener = $rootScope.$on("someEventYouListenTo", function (event, data) {
  console.log('Event received by ' + $scope.name);
});

$scope.$on('$destroy', function () {
    // Remove the listener$scope.systemListener();
});

Now those old scopes/views won't react to events anymore.

Hope that helps someone!

Post a Comment for "Stop Angularjs From Creating New Controller/$scope Cache And Use Cached One"