code to create tabs component 嗨,我正在从这个链接学习角度组件,问题是当我试图从外部文件加载而不是模板时,它会抛出以下错误
angular.js:13708 TypeError: Cannot set property 'selected' of undefined
at controller.selectTab (scr.js:47)
at controller.$postLink (scr.js:50)
at angular.js:9228
at forEach (angular.js:329)
at nodeLinkFn (angular.js:9225)
at compositeLinkFn (angular.js:8510)
at compositeLinkFn (angular.js:8513)
at compositeLinkFn (angular.js:8513)
at publicLinkFn (angular.js:8390)
at angular.js:1756
这是scr.js代码
var tab = {
bindings: {
label: '@'
},
require: {
tabs: '^^tabs'
},
transclude: true,
template:['$templateCache',function($templateCache){
return $templateCache.get('tab.html')
}
],
controller: function () {
this.$onInit = function () {
this.tab = {
label: this.label,
selected: false
};
this.tabs.addTab(this.tab);
};
}
};
var tabs = {
bindings: {
selected: '@'
},
transclude: true,
template:['$templateCache',function($templateCache){
return $templateCache.get('tab.html')
}
],
controller: function () {
this.$onInit = function () {
this.tabs = [];
};
this.addTab = function addTab(tab) {
this.tabs.push(tab);
};
this.selectTab = function selectTab(index) {
for (var i = 0; i < this.tabs.length; i++) {
this.tabs[i].selected = false;
}
this.tabs[index].selected = true;
};
this.$postLink = function () {
this.selectTab(this.selected);
console.log(this.selected)
};
},
};
angular
.module('app', [])
.component('tab', tab)
.component('tabs', tabs);
这是html代码:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>
<script src="scr.js"></script>
<style>
* {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
body {
font: 300 14px/1.4 'Helvetica Neue', Helvetica, Arial, sans-serif;
background: #111;
margin: 0;
padding: 0;
}
.tabs {
margin: 25px;
background: #fff;
}
.tabs__list {
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
border-bottom: 1px solid #eee;
}
.tabs__list li {
float: left;
}
.tabs__list li a {
color: #444;
display: block;
text-decoration: none;
padding: 10px 20px;
}
.tabs__content {
padding: 10px;
}
</style>
</head>
<body>
<div ng-app="app">
<div>
<tabs selected="2">
<tab label="Tab 1">
Tab 1 contents!
</tab>
<tab label="Tab 2">
Tab 2 contents!
</tab>
<tab label="Tab 3">
Tab 3 contents!
</tab>
</tabs>
</div>
</div>
</body>
</html>
这里有两个模板,我试图分别在组件tab.html和tabs.html中加载:
<div class="tabs__content" ng-if="$ctrl.tab.selected">
<div ng-transclude></div>
</div>
<div class="tabs">
<ul class="tabs__list">
<li ng-repeat="tab in $ctrl.tabs">
<a href=""
ng-bind="tab.label"
ng-click="$ctrl.selectTab($index);"></a>
</li>
</ul>
<div class="tabs__content" ng-transclude></div>
</div>
任何人都可以帮我解决这个问题,提前致谢