Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

md-tabs loosing scope when the object its repeating on is changed [AngularJS Material]

Please take a look at this codepen

As soon as you click on UseDummy2 btn which does nothing but change the variable on which the md-tabs is repeating on, I loose the $scope.selectedIndex value. The $scope.selectedIndex is reset to 0 and the first tab is selected.

How can I maintain the selected tab even after changing $scope.lineDirections?

I have tried using $rootScope.selectedIndex but still does not work.

like image 799
Manish Pradhan Avatar asked Jun 24 '17 18:06

Manish Pradhan


1 Answers

ng-tab have watcher for the array "lineDirections", in this watcher they are reseting the value of attr md-selected ("selectedIndex"), you can maintain it by using closure as follow :

 $scope.useDummyArray1 = function () {
      var selectedIndex = $scope.selectedIndex;
      $timeout(function(){
        $scope.selectedIndex = selectedIndex;
      });
      $scope.lineDirections = $scope.dummyArray1;
    };

do the same in all three function. Timeout code will fire after watcher, which will again set the previous value of "selectedIndex"

you can also do it in following way (but should not use this way, only for verification)

$scope.useDummyArray1 = function () {
    for(var i=0;i<$scope.lineDirections.length;i++){
        $scope.dummyArray1[i].$$hashKey = $scope.lineDirections[i].$$hashKey;
     }
     $scope.lineDirections = $scope.dummyArray1;
};

this will keep the value of $$hashKey unchanged which will prevent angular to fire watcher. but its not recommended for following reason : 1) $$hashKey is used by angular internally, its not a good idea to play with these keys. 2) if your "lineDirections" length is different then there will be case when some $$hashKey will change.

like image 139
pankaj sharma Avatar answered Oct 17 '22 04:10

pankaj sharma