2013-03-20 20 views
1

如何在每次控制器調用之前設置一些模型/變量?在AngularJS的每個控制器調用之前清除一個變量?

目前,我有以下服務,幫助我的網頁上設置錯誤消息(在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!") 

有什麼辦法可以自動化這個清晰的步驟嗎?

回答

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 
相關問題