angularjs - Angular multiple instances of the same controller are created -


in example below can see each time go page new instance of same controller created different id, , old 1 not destroyed, setintervat method keeps logging corresponding scope id , fruit name on of them. let's have ajax call instead of log, refreshes page's content time time, don't want make calls inactive pages, how can fix this?

example

var app = angular.module('plunker', ['ngroute']);  app.config(['$routeprovider', function($routeprovider) {   $routeprovider     .when('/fruit/:fruitid', {       templateurl: 'fruit-tpl.html',       controller: 'fruitcontroller'     })     .otherwise({       redirectto: '/fruit/1'     }); }]);  app.controller('fruitcontroller', ['$scope', '$routeparams',   function($scope, $routeparams) {     var fruitarr = ['lemons', 'oranges', 'grapefruit'],         fruitid = $routeparams.fruitid - 1;      $scope.fruitname = fruitarr[fruitid];      setinterval(function() {       console.log('scope', $scope.$id, $scope.fruitname);     }, 3000);   } ]); 

setinterval not stopped automatically when controller destroyed, , until stopped, variables closed on closure pass remain in memory. if switched $interval, same problem persist.

note: intervals created service must explicitly destroyed when finished them. in particular not automatically destroyed when controller's scope or directive's element destroyed. should take consideration , make sure cancel interval @ appropriate moment. see example below more details on how , when this.

var theinterval = setinterval(function() {   console.log('scope', $scope.$id, $scope.fruitname); }, 3000); $scope.$on('$destroy', function() {   // make sure interval destroyed   clearinterval(theinterval); }); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -