Using ng-init to call controller functions and passing vars between controllers

3k views Asked by At

The below method works...however, it only does so with $timeout added to the tabList() function. The ng-init is executing before the DOM renders thus the document.getElementById('')'s is coming back as undefined. I must force a delayed timer of 1 to 2 seconds until the DOM loads before appending the elements. This is not optimal but it does work. I am looking for another method that is cleaner and not dependent on delayed execution.

angular.module('starter.controllers', [])

.constant('constants', {
   tabColors: {
     curID:0,
   },
})

.controller('TabsCtrl', function($scope,Tabs,constants) {  
  $scope.constants = constants; 
  $scope.tabList = function() {
        var tID = $scope.constants.tabColors ;
    console.log(tID.curID) ;
    if (tID.curID) {
        $timeout(function() {
        document.getElementById('bike_tabItem_'+tID.curID).style.color = 'green' ;
        document.getElementById('bike_tabItem_'+tID.curID).style.color = 'black' ;
      },1000) ;
    }
  }
})

.controller('TabDetailCtrl', function($state,$scope,$stateParams,Tabs,constants) {
  $scope.constants = constants; //make it available constants on html
  $scope.itemSelect = function(thisID) {
    $scope.constants.tabColors.oldID = $scope.constants.tabColors.curID ;
    delete $scope.constants.tabColors['tabID_'+$scope.constants.tabColors.curID] ;
    $scope.constants.tabColors.curID = thisID ;
    $scope.constants.tabColors['tabID_'+thisID] = 'green' ;
  }
})

// In HTML on Tab.html :

<ion-item cache-view="false" id="tab_tabItem_{{tab.tabID}}" ng-init="tabList()">

// In HTML on Tab-Detail.html

<button id="tab_button" class="button button-small button-outline button-positive" ng-click="itemSelect({{tab.tabID}});">
Select this item
</button>

On a side note, another way to call tabList() is like: ng-init="tabList('{{tab.tabID}}')"

This gives you a way of passing values through the ng-init which, unlike my above call, gives you better control without having to define globals. Though you would still need a global for the above to track which element was turned green so you could then set it back to black before setting the new element green.

1

There are 1 answers

1
Freezystem On

As said in the AngularJS documentation you should avoid the use of ng-init.

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

To passes variables between controllers you can use a provider.