如何在每次控制器调用之前设置一些模型/变量?
目前,我有以下服务帮助我在页面上设置错误消息(LiveScript中的代码):
angular.module "project.services",
.factory "Message", ($rootScope) ->
{
error : !(msg) -> $rootScope.error = msg
success : !(msg) -> $rootScope.success = msg
clear : !(msg) ->
$rootScope.error = ''
$rootScope.success = ''
}
然后在我的index.html
模板中:
<div ng-show="error" class="alert alert-error">{{error}}</div>
<div ng-show="success" class="alert alert-success">{{success}}</div>
<div ng-view>
但是为了使用它,我必须在每个控制器中调用clear
方法,否则错误会保留在屏幕上:
@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!")
有没有办法让这个明确的步骤自动化?
答案 0 :(得分:1)
如果您想在每次路由更改后清除消息(这似乎符合您的用例),您可以将服务更改为以下内容:
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