In our application, we have multiple controllers assigned to different tabs/pages. I am looking for a way to signal the completion of a task in one controller so that it can be used in another controller. I believe Promises are the solution for this, and I am trying to understand how they work.
I experimented with http://jsfiddle.net/ExN6Q/ and achieved the desired functionality, but I am not entirely satisfied with how the services were implemented.
For example, consider the following HTML structure:
<div ng-app="myApp">
<div ng-controller=myController1>
Fill in this field: <input type="text">
<input type="submit" value="Done" ng-click="submit()">
</div>
<div ng-controller=myController2 ng-show="done1">
And this field: <input type="text">
<input type="submit" value="Done" ng-click="submit()">
</div>
<div ng-controller=myController3 ng-show="done2">
As well as this field: <input type="text">
<input type="submit" value="Done" ng-click="submit()">
</div>
</div>
and the corresponding controllers:
my_module.controller('myController1', function ($scope, Done1Service) {
$scope.submit = Done1Service.done;
});
my_module.controller('myController2', function ($scope, Done1Service, Done2Service) {
$scope.done1 = false;
$scope.submit = Done2Service.done;
Done1Service.get_promise().then(function () {
$scope.done1 = true;
});
});
my_module.controller('myController3', function ($scope, Done2Service, Done3Service) {
$scope.done2 = false;
$scope.submit = Done3Service.done;
Done2Service.get_promise().then(function () {
$scope.done2 = true;
});
Done3Service.get_promise().then(function () {
alert("Congratulations, you're done!");
});
});
While I am happy with the result, I feel that the implementation of the services is too repetitive. Is there a better approach, such as creating a single common service and instantiating it three times? Should I rename the get_promise function to make it more descriptive?