AngularJS
v. 1.2.14, Bootstrap v3.3.1
In my web
page, I have this HTML code that defines a tab panel control like this:
<div ng-controller="PanelController as
panelCtrl">
<ul class="nav nav-tabs">
<li ng-class="{
active:panelCtrl.isSelected(1)}">
<a ng-click="panelCtrl.selectTab(1)">Tab 1</a>
</li>
<li ng-class="{
active:panelCtrl.isSelected(2)}">
<a ng-click="panelCtrl.selectTab(2)">Tab 2</a>
</li>
<li ng-class="{
active:panelCtrl.isSelected(3)}">
<a ng-click="panelCtrl.selectTab(3)">Tab 3</a>
</li>
</ul>
<div class="tab-content">
<div class="panel" ng-show="panelCtrl.isSelected(1)">
<div>
<br />
</div>
</div>
<div class="panel" ng-show="panelCtrl.isSelected(2)">
<div>
<br />
</div>
</div>
<div class="panel" ng-show="panelCtrl.isSelected(3)">
<div class="clearfix">
<br />
</div>
</div>
</div>
</div>
Then in my
javascript module (app.js) there is the controller “PanelController” definition:
(function() {
angular.module('app', [
'ui.bootstrap'
])
.controller('PanelController', ['$scope', function ($scope) {
var self = this;
self.tab
= 1;
self.selectTab
= function(setTab) {
self.tab
= setTab;
};
self.isSelected
= function(checkTab) {
return self.tab === checkTab;
};
$scope.$on('defaultTab', function () {
self.tab
=sharedPanelService.tab;
});
}])
})();
Well, now I
want to implement an event when the user click on a TAB, for example the Tab 3 and
for this purpose, I have added this factory:
.factory('sharedPanelService', function($rootScope) {
var sharedPanelService = {};
sharedPanelService.prepForBroadcastClickItem
= function (tab) {
this.tab = tab;
this.broadcastClickItem();
};
sharedPanelService.broadcastClickItem
= function () {
$rootScope.$broadcast('clickTab');
};
return sharedPanelService;
})
and I have
modified the “PanelController” in this way, adding this statement
sharedPanelService.prepForBroadcastClickItem(setTab);
The new “PanelController” is:
.controller('PanelController', ['$scope', 'sharedPanelService', function ($scope, sharedPanelService) {
var self = this;
self.tab
= 1;
self.selectTab
= function(setTab) {
self.tab
= setTab;
sharedPanelService.prepForBroadcastClickItem(setTab);
};
self.isSelected
= function(checkTab) {
return self.tab === checkTab;
};
$scope.$on('defaultTab', function () {
self.tab
=sharedPanelService.tab;
});
}])
where I
have injected the sharedPanelService
Finally in
the javascript module (customer.js) where I want to intercept the click event I
have injected the sharedPanelService and modified the code like this:
(function() {
angular.module('customer', ['ui.bootstrap'])
.controller('CustomerController', [
'$scope', 'sharedPanelService',
function($scope, sharedPanelService) {
$scope.$on('clickTab', function() {
var tabSelected =
sharedPanelService.tab;
// If Tab 3.
if (tabSelected === 3) {
// Todo something
...
}
});
}
]);
})();
Kind regards!
Nessun commento:
Posta un commento