I am building an app in angular, which consumes different APIs and Gives options for the user to select it will be recorded and sent back to the server.
I have designed it as follows.
- All the common logic in Main Controller and all other options in different controllers as the child of main controller.
- Main Controller retrieve all the data that are required to run the app. which is consumed by all other child controllers.
- To make sure data is loaded I am using promise attached to scope. So all the child controller will know data loaded.
- I have moved data updation part of all child controllers to main controller because all the updates happen in one object.
- Child Controller emit/broadcast to communicate between child and main. So when update happens child will emit an event with data which will be captured by Main and it will do the update.
MainController { $scope.loaded = DataService.get(); $scope.userOptions = {}; $scope.$on('update',function(){ updateUserOptions(); }) } ChildController { $scope.loaded.then(function(){ //all logic of child controller } $scope.onselect = function(){ $scope.$emit('update',data); } }
Questions
- Is it a good practice to use events between controllers ?
- is it good to use promise attached to scope for child controllers ?
- Will it improve my code if I start using services ?