In our current AngularJS application, we have three tabs and 3 different controllers are used to bind them.
var myApp = angular.module('MyApp',[]);
myApp.controller('Tab1Ctrl', function(){
// logic to initialize Tab1
});
myApp.controller('Tab2Ctrl', function(){
// logic to intialize Tab2
});
myApp.controller('Tab3Ctrl', function(){
// logic to initialize Tab3
});
Our intent is to merge these controllers into a single one but initialize these 3 tabs accordingly. We're using resolve
in ui-router
for this. All the data that is required for a particular tab is loaded within resolve and current state name is saved in MyService
.
myApp.config(function($stateProvider){
$stateProvider.state('tab1', {
url: '/tab1',
controller: 'TabCtrl',
templateUrl: 'tab1.html',
resolve: {
tabData: function(MyService) {
MyService.setState('tab1');
return MyService.getTab1Data();
}
}
}).state('tab2', {
url: '/tab2',
controller: 'TabCtrl',
templateUrl: 'tab2.html',
resolve: {
tabData: function(MyService) {
MyService.setState('tab2');
return MyService.getTab2Data();
}
}
});
});
myApp.controller('TabCtrl', function($scope, MyService, tabData){
/* Check for state name and initialize */
if(MyService.getState() === 'tab1'){
/* Use the data loaded in resolve and assign it to scope*/
$scope.tab1Prop = tabData.prop1;
}
else if(MyService.getState() === 'tab2'){
/* Use the data loaded in resolve and assign it to scope*/
$scope.tab2Prop = tabData.prop2;
}
});
Note that properties that we need to set on $scope
are differentfor each tab.
Finally my question is, Is there any better way to do this conditional initialization in a single controller ?
No comments:
Post a Comment