最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop AngularJs from creating new controller$scope cache and use cached one - Stack Overflow

programmeradmin9浏览0评论

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?

Explanation:

/ (click on links)

<a href='#'>First controller</a>
<a href='#/view'>Second controller</a>

$routeProvider.
  when('/', { template:"{{$id}}",controller: ContentListCtrl}).
  when('/view', {template:"{{$id}}",controller: ContentDetailCtrl}).

P.s. is it possible to know which controller is currently active?

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?

Explanation:

http://jsfiddle/mpKBh/1/ (click on links)

<a href='#'>First controller</a>
<a href='#/view'>Second controller</a>

$routeProvider.
  when('/', { template:"{{$id}}",controller: ContentListCtrl}).
  when('/view', {template:"{{$id}}",controller: ContentDetailCtrl}).

P.s. is it possible to know which controller is currently active?

Share Improve this question asked Mar 5, 2013 at 20:20 ArtūrasArtūras 4734 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

For those researching how to "unbind" in AngularJS, he is a bit of info (related to the OP's last ment 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!

发布评论

评论列表(0)

  1. 暂无评论