当重复的对象被更改时,md-tabs丢失范围[AngularJS Material]

Man*_*han 6 javascript angularjs angularjs-material

请看看这个codepen

只要你单击UseDummy2 btn,它只会更改md-tabs重复的变量,但我会松开该$scope.selectedIndex值.将$scope.selectedIndex被复位为0,并选择第一选项卡.

即使在更改$ scope.lineDirections后,如何维护选定的选项卡?

我尝试过使用$ rootScope.selectedIndex但仍然无法正常工作.

小智 3

ng-tab 有数组“lineDirections”的观察者,在这个观察者中,他们正在重置 attr md-selected (“se​​lectedIndex”) 的值,您可以通过使用闭包来维护它,如下所示:

 $scope.useDummyArray1 = function () {
      var selectedIndex = $scope.selectedIndex;
      $timeout(function(){
        $scope.selectedIndex = selectedIndex;
      });
      $scope.lineDirections = $scope.dummyArray1;
    };
Run Code Online (Sandbox Code Playgroud)

在所有三个函数中执行相同的操作。超时代码将在观察者之后触发,这将再次设置“selectedIndex”的先前值

您也可以通过以下方式进行(但不应该使用这种方式,仅用于验证)

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

这将使 $$hashKey 的值保持不变,从而防止 Angular 触发观察者。但不建议这样做,原因如下:1)$$hashKey 由 Angular 内部使用,使用这些键不是一个好主意。2)如果您的“lineDirections”长度不同,那么某些 $$hashKey 会发生变化。