创建和选择角度材料选项卡

ada*_*eks 2 javascript angularjs material-design angular-material

我目前正在使用该指令的md-selected属性md-tabs来控制哪个选项卡是选定的选项卡.当我创建一个新选项卡时,我想选择新创建的选项卡.这适用于我已经包含的演示,但会引发错误.有没有更好的办法?

JS:

$scope.addTab = function (title, view) {
  view = view || title + " Content View";
  var newIndex = tabs.push({ title: title, content: view, disabled: false});
  $scope.selectedIndex = newIndex;
};
Run Code Online (Sandbox Code Playgroud)

HTML:

<md-tabs md-selected="selectedIndex" md-border-bottom="">
  <md-tab ng-repeat="tab in tabs" ng-disabled="tab.disabled" label="{{tab.title}}">
Run Code Online (Sandbox Code Playgroud)

错误:

TypeError: Cannot read property 'offsetLeft' of undefined
at updateInkBarStyles (angular-material.js:12808)
at Object.handleSelectedIndexChange [as fn] (angular-material.js:12750)
at Scope.$get.Scope.$digest (angular.js:14308)
at Scope.$get.Scope.$apply (angular.js:14571)
at HTMLFormElement.<anonymous> (angular.js:21571)
at HTMLFormElement.eventHandler (angular.js:3032)
Run Code Online (Sandbox Code Playgroud)

http://codepen.io/anon/pen/JdbLda

Ton*_*ony 5

我发现的主要问题是你newIndex的添加不是基于0的,因为push返回新的长度:

var newIndex = tabs.push({ title: title, content: view, disabled: false});
$timeout(function() {
  $scope.selectedIndex = newIndex - 1;
});
Run Code Online (Sandbox Code Playgroud)

我将更改包装在一个$timeout,否则tabs还没有更新,并抛出一个未定义的错误.

我也改变了previousselected只是他们各自的索引而不是一个完整的标签(你可以选择任何一种方式,只要确保你知道你何时比较int一个tab对象!).而且,在第一关,selectednull:

previous = selected || old;
Run Code Online (Sandbox Code Playgroud)

你可以在这个codepen上看到整个事情!