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

时间:2015-05-26 20:54:05

标签: 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;
};

HTML:

<md-tabs md-selected="selectedIndex" md-border-bottom="">
  <md-tab ng-repeat="tab in tabs" ng-disabled="tab.disabled" label="{{tab.title}}">

错误:

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)

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

2 个答案:

答案 0 :(得分:5)

我发现的主要问题是,添加中的newIndex不是基于0,而是push returns the new length

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

我将更改包含在$timeout中,否则tabs尚未更新,并引发未定义的错误。

我还将previousselected更改为他们各自的索引而不是完整标签(您可以选择其中一种方式,只需确保您知道何时比较{ {1}}到int个对象!)。并且,在第一次传递时,tabselected

null

您可以在此codepen上看到整个内容!

答案 1 :(得分:3)

自此问题发布以来,他们已添加md-autoselect标记:

  

md-autoselect 布尔
  如果存在,将自动选择在初始加载后添加的任何选项卡