【问题标题】:AngularJs: pass $scope variable with serviceAngularJs:通过服务传递 $scope 变量
【发布时间】:2016-05-26 02:57:23
【问题描述】:

我有两个控制器,我在其中一个控制器中声明了一个 $scope 变量,我希望它在第二个控制器中可见。

第一个控制器

app.controller('Ctrl1', function ($scope) {
    $scope.variable1 = "One";
});

第二控制器

app.controller('Ctrl2', function ($scope, share) {
   console.log("shared variable " + share.getVariable());
});

我研究了最好的 Angular 方法,我发现那是服务的使用。所以我为Ctrl1添加了一个服务

服务

.service('share', function ($scope) {
    return {
        getVariable: function () {
            return $scope.variable1;
        }
    };
});

此代码返回此错误:

Unknown provider: $scopeProvider <- $scope <- share

所以我的问题是:控制器之间是否可以共享 $scope 变量?不是最好的 Angular 解决方案还是我遗漏了什么?

很抱歉我的小问题,但我是 Angular 初学者。

提前致谢

问候

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-service


    【解决方案1】:

    是的,可以通过服务和工厂在控制器之间共享范围变量。但是,$scope 变量是控制器本身的本地变量,服务无法知道该特定变量。我更喜欢使用工厂,像黄油一样容易和光滑。如果您在单独的文件中使用工厂服务,则需要将该文件包含在 index.html 中

     app.controller('Ctrl1', function ($scope,myService,$state) {
            $scope.variable1 = "One";
            myService.set($scope.variable1);
            $state.go('app.thepagewhereyouwanttoshare');//go to the page where you want to share that variable.
        });
    
     app.controller('Ctrl2', function ($scope, myService) {
       console.log("shared variable " + myService.get());
    });
        .factory('myService', function() {
          function set(data) {
            products = data;
          }
          function get() {
            return products;
          }
    
          return {
            set: set,
            get: get
          }
    
        })
    

    【讨论】:

      【解决方案2】:

      您不能在服务工厂函数中注入 $scope 依赖项。

      基本上可共享的服务应该在某个对象中维护可共享的数据。

      服务

      .service('share', function () {
          var self = this;
          //private shared variable
          var sharedVariables = { };
          self.getSharedVariables = getSharedVariables;
          self.setVariable = setVariable;
      
          //function declarations
          function getSharedVariables() {
              return sharedVariables;
          }
          function setVariable() {
              sharedVariables[paramName] = value;
          }
      });
      

      控制器

      app.controller('Ctrl1', function ($scope, share) {
          $scope.variable1 = "One";
          share.setVariable('variable1', $scope.variable1); //setting value in service variable
      });
      
      app.controller('Ctrl2', function ($scope, share) {
          console.log("shared variable " + share.getSharedVariables());
      });
      

      【讨论】:

        【解决方案3】:

        您尝试使用服务非常好,但您不应该尝试使用 $scope 将依赖项注入到服务代码中。 Service 是你的数据提供者,如果你想在 2 个控制器之间共享一些数据,你应该在你的服务中为这些数据留出位置

        .service('share', function ($scope) {
            this.variable1 = '';
            return {
                getVariable: function () {
                    return this.variable1;
                }
                setVariable(variable)
                {
                    this.variable1 = variable;
                }
            };
        });
        
        app.controller('Ctrl1', function (share) {
            $scope.variable1 = share.getVariable();
        });
        

        这是此解决方案的更广泛描述: https://stackoverflow.com/a/21920241/4772988

        【讨论】:

          【解决方案4】:

          最好的方法是真正使用服务。服务只能访问$rootScope,它们没有自己的$scope

          但是,您不应为此任务使用范围。只需在任何范围之外使用一些共享变量创建服务即可。

          .service('share', function ($scope) {
          
              var variable = 42;
          
              return {
                  getVariable: function () {
                      return variable;
                  }
              };
          });
          
          app.controller('Ctrl', function ($scope, share) {
              console.log("shared variable " + share.getVariable());
          
              // Watch for changes in the service property
              $scope.$watch(function() { return share.getVariable(); }, function(oldValue, newValue) {
                  // whatever
              });
          });
          

          【讨论】:

            【解决方案5】:

            首先,你的服务应该是这样的:

            app.service('share', function () {
                // this is a private variable
                var variable1;
                return {
                    // this function get/sets the value of the private variable variable1
                    variable1: function (newValue) {
                        if(newValue) variable1 = newValue;
                        return variable1;
                    }
                };
            });
            

            要设置共享变量的值,请将值传递给我们在服务上创建的函数

            app.controller('Ctrl1', function ($scope, share) {
                $scope.variable1 = "One";
                // share the value of $scope.variable1
                share.variable1($scope.variable1);
            });
            

            要获取共享变量的值,也可以使用服务中的函数而不传递值

            app.controller('Ctrl2', function ($scope, share) {
                console.log("shared variable " + share.variable1());
            });
            

            【讨论】:

              【解决方案6】:

              更新:使用 $rootScope 被认为是不好的做法。

              您需要的是$rootScope$scope 仅适用于一个控制器。这是一个例子:

              angular.module('myApp', [])
              .run(function($rootScope) {
                  $rootScope.test = new Date();
              })
              .controller('myCtrl', function($scope, $rootScope) {
                $scope.change = function() {
                      $scope.test = new Date();
                  };
              
                  $scope.getOrig = function() {
                      return $rootScope.test;
                  };
              })
              .controller('myCtrl2', function($scope, $rootScope) {
                  $scope.change = function() {
                      $scope.test = new Date();
                  };
              
                  $scope.changeRs = function() {
                      $rootScope.test = new Date();
                  };
              
                  $scope.getOrig = function() {
                      return $rootScope.test;
                  };
              });
              

              【讨论】:

              • 污染 $rootScope 被认为是不好的做法,类似于为什么全局变量被认为是不好的做法。请改用服务/工厂。
              • 是的,这是真的。但我认为这是他要求的。但在某些情况下它很有用
              • 我认为 OP 的问题是关于如何使用 service 在控制器之间共享数据。
              猜你喜欢
              • 2014-09-28
              • 1970-01-01
              • 1970-01-01
              • 2015-11-19
              • 2014-05-09
              • 1970-01-01
              • 1970-01-01
              • 2016-11-28
              • 1970-01-01
              相关资源
              最近更新 更多