我有一个标签视图的指令。当我尝试隔离范围时,它不起作用。为什么会这样?
目前,范围部分已被注释掉并且工作正常。
当我隔离范围时,它不会调用函数loadTab()
myApp.directive("tabsPanel", () => {
return {
restrict: "E",
replace: true,
// scope: {
// tabs: "=tabs",
// activeTab: "=",
// loadTab: "&"
// },
transclude: true,
link: (scope, element, attrs) => {
console.log(scope);
},
templateUrl: "views/tabs-panel.html"
}
});
当我隔离范围时,它在console.log中显示的内容:
activeTab: undefined
loadTab: (locals)
tabs: Array[4]
templateUrl:
<div class="tabs-panel">
<div class="tab-wrapper">
<ul class="tabs-nav">
<li ng-repeat="tab in tabs">
<a href class="tablinks" ng-bind="::tab.name" ng-click="loadTab({currentTab: tab})" ng-class="{'selected-tab' : activeTab === tab}"></a>
</li>
</ul>
<match-history-tab ng-show="activeTab.url === 'history'"></match-history-tab>
<odd-movements-tab ng-show="activeTab.url === 'odds'"></odd-movements-tab>
<injuries-and-suspensions-tab ng-show="activeTab.url === 'injury'"></injuries-and-suspensions-tab>
<week-stats-tab ng-show="activeTab.url === 'general'"></week-stats-tab>
</div>
</div>
使用标签面板的HTML:
<div class="main-panel">
<tabs-panel tabs="tabs"></tabs-panel>
</div>
被叫函数:
$scope.loadTab = (selectedTab) => {
if(selectedTab) {
activeTab = selectedTab.currentTab;
} else {
$scope.activeTab = $scope.tabs[0];
}
};
答案 0 :(得分:2)
看下面的示例代码片段,如何从隔离范围调用函数。 您没有将功能分配给隔离范围变量(load-tab)
像这样 <tabs-panel load-tab="loadTab(data)"></tabs-panel>
var app = angular.module("myapp",[]);
app.directive("tabsPanel", () => {
return {
restrict: "E",
replace: true,
scope: {
tabs: "=tabs",
activeTab: "=",
loadTab: "&"
},
transclude: true,
link: (scope, element, attrs) => {
},
template: "<h2 ng-click='loadTab({data:\"world\"})'>click here</h2>"
}
});
app.controller('todoCtrl',function($scope){
$scope.loadTab = function(data){
alert("hello " +data);
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="todoCtrl">
<tabs-panel load-tab="loadTab(data)"></tabs-panel>
</div>
</div>
&#13;