在视图之间传递对象(flash消息)

bsr*_*bsr 14 javascript angularjs

在下面的场景中传递消息的最佳方法是什么.

在成功场景中$scope.p.$save,结果包含一条message(res.message),我想在下一个视图中显示($location.path("/test/"+res.reply.Id)).没有AngularJS,我可以在URL中传递它或将其保存在会话cookie中.但是,我想AngularJS可能有更好的方法,因为没有浏览器重定向,状态应该可用.实现这一目标的最佳方法是什么?

在rootScope中设置它会在我使用浏览器后退按钮时显示它,并且消息的范围应仅用于第一次导航到新视图.

function NewCtrl(Phone, $location, $rootScope, $scope) {
    $scope.p = new Phone();
    $scope.save = function () {
        $scope.p.$save(
            {},
            function (res) {
                $rootScope.message = res.message **//<-- this will cause message still set when using browser back button, etc**
                $location.path("/test/"+res.reply.Id); **//<-- Req: needs to pass the message to next view**
            }, function (res) {
            //TODO
            }
        );
    };
}
....
PhoneApp.factory('Phone', function ($resource) {
    return $resource('/api/test/:_id')
});
Run Code Online (Sandbox Code Playgroud)

And*_*lin 16

您可以使用在$ routeChangeSuccess上显示闪存的服务.

每次设置Flash消息时,将其添加到队列中,当路由更改时,将第一个项目从队列中取出并将其设置为当前消息.

这是一个演示:

http://plnkr.co/edit/3n8m1X?p=preview


Wil*_*ent 5

我当时想要实现类似的功能,但实际上想要更多的咆哮风格消息.

我已经更新了Andy提供的优秀plinkr代码,其中包含一个利用toastr growl风格通知库的"pop"方法.

我的更新还允许您指定通知类型(信息,警告,成功,错误)和标题.

'pop'方法会跳过将消息添加到队列中,而是立即将其弹出屏幕.Andy之前的plinkr的set/get功能基本保持不变.

您可以在此处找到我的更新:http://plnkr.co/edit/MY2SXG?p = preview