Help in tabs - init function


#1

Hi,

I have tabs:

...
$stateProvider

    // setup an abstract state for the tabs directive
    .state('tab', {
      url: "/tab",
      abstract: true,
      templateUrl: "templates/tabs.html"
    })

    // the home tab has its own child nav-view and history
    .state('tab.home-index', {
      url: '/home',
      views: {
        'home-tab': {
          templateUrl: 'templates/home-index.html',
          controller: 'HomeIndexCtrl'
        }
      }
    })

    .state('tab.calculator', {
      url: '/info',
      views: {
        'info-tab': {
          templateUrl: 'templates/info.html'
        }
      }
    })
...

in controllers:

...
.controller('HomeIndexCtrl', function($scope, $ionicLoading, $timeout, $http) {
  
  	$scope.init = function() {
                //something get data from remote with $http
        }
	 $scope.init();
  
});
...

then, when I go to the “Info” tab and then back to “Home” runs init (), but I wish not to run init ().

Please I need help.


#2

Because of the way you wrote the $scope.init, it will happen EVERY time the state changes. The controller loads and runs $scope.init().

If you only want this to happen once, you will need to use a service to check whether or not the init has ever happened. Untested example:

.factory('InitService', function() {
	var hasInited = false;
	return hasInited;
})

.controller('HomeIndexCtrl', function($scope, $ionicLoading, $timeout, $http, InitService ) {


  	$scope.init = function() {
        //something get data from remote with $http	
        InitService.hasInited = true;
    }
	

	if(! InitService.hasInited ) $scope.init();

});

#3

Thank you!!!, I found other way

using $rootScope

if(($rootScope.data)) $scope.init();


#4

Maybe scope.init solve TypeError: parent is null when load json data and update a template view?