gpt4 book ai didi

javascript - 在 AngularJS 中每次调用 Controller 之前清除变量?

转载 作者:行者123 更新时间:2023-11-28 02:21:54 25 4
gpt4 key购买 nike

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

目前我有以下服务来帮助我在页面上设置错误消息(代码在 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>

但是为了使用它,我必须在每个 Controller 中调用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!")

有什么方法可以自动完成这个明确的步骤吗?

最佳答案

如果您想在每次路由更改后清除消息(这似乎适合您的用例),您可以将您的服务更改为如下所示:

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

关于javascript - 在 AngularJS 中每次调用 Controller 之前清除变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15528764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com