1

如何在每次控制器调用之前设置一些模型/变量?

目前,我有以下服务可以帮助我在页面上设置错误消息(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!")

有没有办法自动化这个清晰的步骤?

4

1 回答 1

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
于 2013-04-30T15:23:31.853 回答