繁体   English   中英

在Angular JS中的控制器之间共享数据?

[英]Sharing data between controllers in Angular JS?

在将此标记为重复之前,我已经阅读了很多类似的问题,但是我发现的所有答案似乎都使​​用$ scope,并且在阅读了文档之后,我不确定自己是否理解$ scope,或者为什么我知道d在这种情况下使用它。

我发现本教程描述了如何做我想做的事情。

但是,它使用的是数据数组。 我只需要一个实数变量。 另外,我不知道他为什么要为他创建的工厂服务声明一个附加对象; 为什么不仅仅使用工厂作为对象?

我当时以为可以做这样的事情,但是我不确定它是否会起作用。

创建我的工厂/服务:

var demoModule = angular.module("demoModule", []);

demoModule.factory("demoService", function() {
     var demoSharedVariable = null;
     return demoSharedVariable;
});

访问每个控制器中的共享变量:

var demoControllerOne = demoModule.controller("demoContollerOne", function(demoSharedVariable) {
     this.oneFunction = function(oneInput){
          demoSharedVariable = oneInput;
     };
});

var demoControllerTwo = demoModule.controller("demoContollerTwo", function(demoSharedVariable) {
     this.twoFunction = function(twoInput){
          demoSharedVariable = twoInput;
     };
});

这种方法会产生我想要的共享变量吗?

您需要注入服务才能使用它,然后访问服务变量。

demoModule.controller("demoContollerOne", function($scope, demoService) {
  $scope.oneFunction = function(){
    demoService.demoSharedVariable = $scope.oneInput;
  };
});

demoModule.controller("demoContollerTwo", function($scope, demoService) {
  $scope.twoFunction = function(){
    demoService.demoSharedVariable = $scope.twoInput;
  };
});

如果使用controllerAs,则很少(或不应)注入并使用$ scope。 由于controllerAs是一个相对较新的功能,所以那时我们别无选择,只能使用$ scope,因此使用$ scope查找示例并不奇怪。


编辑:如果您不使用controllerAs(如本例中所示),则需要$ scope将函数或变量公开给视图。

摆弄它时,有几个地方不正确,我将编辑代码。 我不知道如何在不使用$ watch等高级概念的情况下展示效果,如果您不了解,请提供您自己的小提琴。

吉斯宾

重要的一件事是,如果您想使用角度,则必须了解范围的知识。

由于您的工厂或控制器都不正确,因此我为您编写了一个简单的示例来帮助您了解服务:

此plnkr中的详细实现

服务:

angular.module('myApp').service('MyService', [function() {

      var yourSharedVariable; // Your shared variable

      //Provide the setter and getter methods
      this.setSharedVariable = function (newVal) {
        yourSharedVariable = newVal;
      };

      this.getSharedVariable = function () {
        return yourSharedVariable;
      };

    }
]);

控制器:

myApp.controller('Ctrl2', ['$scope', 'MyService', '$window', function($scope, MyService, $window) {//inject MyService into the controller
    $scope.setShared = function(val) {
      MyService.setSharedVariable(val);
    };

    $scope.getShared = function() {
      return MyService.getSharedVariable();
    };

    $scope.alertSharedVariable = function () {
      $window.alert(MyService.getSharedVariable());
    };

}]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM