本文介绍了使用 Angular 服务在控制器之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让两个不同的控制器相互通信.

I am trying to have two different controllers communicate with each other.

控制器 1

function WelcomeCtl($scope, emailService) {
    $scope.save=function(){
        emailService.saveEmail(‘Hi’);
        }
}

WelcomeCtl.$inject = [$scope, emailService];

此控制器旨在从文本字段中获取文本(使用 ng-model = 'email')并将文本放入服务 (emailService) 中,以便它可以在下一个 ng-view(受控制)中使用由下一个控制器)//出于测试目的,我只是将Hi"直接放入 saveEmail 函数中

This controller is designed to take the text from a text field (with ng-model = ‘email’) and put the text into a service (emailService) so it can be used in the next ng-view (which is controlled by the next controller)//for testing purposes I am just putting ‘Hi’ directly into the saveEmail function

控制器 2

function SignupCtl($scope, emailService) {
    window.alert(emailService.getEmail())
}

SignupCtl.$inject = [$scope, emailService];

出于测试目的,我使用 window.alert 来显示 getEmail() 的值

电子邮件服务

angular.module('myApp.services', [])
       .service('emailService', function (){
           var text ="start value";
           return{
               saveEmail:function (data){
                  text  = data;

              },
              getEmail:function (){
                  return text;
              }
          };
      });

由于使用此服务指定的 Controller1 和 Controller 2,window.alert 打印出起始值"而不是Hi"

As a result of using Controller1 and Controller 2 as specified with this service, window.alert prints out "start value" instead of ‘Hi’

当我在代码中添加更多 window.alert 函数以查看发生了什么时,我看到当调用 save() 时,控制器 1 执行并将值保存到服务中,然后 express.js 加载下一页.然后 Controller2 激活.当控制器 2 激活时,它会重新初始化服务,将文本设置回起始值".然后当 getEmail 被调用时,它返回值起始值"

When I put more window.alert functions in the code to see what is happening I see that when save() is called, Controller 1 executes and saves a value into the service and express.js loads the next page. Then Controller2 activates. When Controller 2 activates it reinitializes the service, setting text back to "start value". Then when getEmail is called it return the value "start value"

这让我很困惑,因为我的印象是每次将服务包含在控制器中时都不会初始化.

This confuses me because I was under the impression that services were not initialized every time the were included in a controller.

查阅资源.
更好的传球设计数据到其他 ng-view 并在控制器之间持久化

我也在使用 angular-express-seedhttps://github.com/btford/angular-express-seed

推荐答案

Angular.js 只能在一个页面上工作和保存数据.如果您的页面重新加载(正如您在说express.js 加载下一页"时似乎表明的那样),那么它会重新初始化所有内容.

Angular.js only works and keeps data on a single page. If your page reloads (as you seem to indicate when you say "express.js loads the next page", then it reinitialized everything.

你应该:

  • look at how to use Angular.js routing (http://docs.angularjs.org/tutorial/step_07) so that you stay on the same page.
  • use something to persist your data, such as localstorage. Find out more: http://diveintohtml5.info/storage.html

这篇关于使用 Angular 服务在控制器之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 01:00