How can I set some model/variable before every controller call?
Currently I have the following service to help me set error messages on the page (code in LiveScript):
angular.module "project.services",
.factory "Message", ($rootScope) ->
{
error : !(msg) -> $rootScope.error = msg
success : !(msg) -> $rootScope.success = msg
clear : !(msg) ->
$rootScope.error = ''
$rootScope.success = ''
}
and then in my index.html template:
<div ng-show="error" class="alert alert-error">{{error}}</div>
<div ng-show="success" class="alert alert-success">{{success}}</div>
<div ng-view>
But in order to use it, I have to call the clear method in every controller, otherwise the error stays on screen:
@SomeController = !($scope, $http, Message) ->
Message.clear() # <--- have to do this
... rest of the controller code
if some-error condition
Message.error("Could not do this")
else
Message.success("Success!")
Is there any way to automate this clear step?
If you want to clear the message after every route change, which seems to fit your use case, you can change your service to something like this:
angular.module "project.services" .factory "Message", ($rootScope) ->
# The Message factory API.
MessageApi = {
error : !(msg) -> $rootScope.error = msg
success : !(msg) -> $rootScope.success = msg
clear : !(msg) ->
$rootScope.error = ''
$rootScope.success = ''
}
# Call Message.clear whenever the route changes.
$rootScope.$on '$routeChangeSuccess', -> MessageApi.clear!
# Return the API.
MessageApi