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

1

6

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.

Airscrew answered 24/6, 2017 at 18:26 Comment(3)
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself.Breakfront
Hi gerogeawg, I believe I have all the components in my original question you mentioned in your comment: desired behaviour: How can I maintain the selected tab even after changing $scope.lineDirections? steps necessary to reproduce the error: 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.Airscrew
@ManishPradhan Your code seems to be working. I am not able to reproduce the errorArroba
M
3

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.

Metzger answered 27/6, 2017 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.