使用 rootscope angular js 在两个控制器之间传递日期

pass date between two controllers using rootscope angular js

我正在使用 $rootScope 来分享我的价值观。请检查我的代码

用户控制器(user.js)

var app = angular.module('myApp', []);
app.controller('user', function($scope,$rootScope) {
 $rootScope.test = "TEST";
});

客户控制者(customer.js)

app.controller('customer', function($scope,$rootScope) {
   $scope.value = $rootScope.test;
            alert($scope.value);
});

这段代码似乎没问题。但结果未定义。我还需要将所有数据保存在控制器中。

我的结果

我如何正确传递这个值

除了用户 $rootScope 在这些控制器之间共享一些数据之外,您还可以使用服务。这是一个例子:

(function () {
    'use strict';

    angular.module('app', []);

    angular.
        module('app')
        .service('contextService', [function () {
            var context = {
                "foo": "bar",
                "hello": "boys"
            };
            var service = {
                getContext: function () {
                    return context;
                },
                getContextValue: function (key) {
                    return context[key];
                },
                setContextValue: function (key, value) {
                    context[key] = value;
                }
            }
            return service;
        }])
        .controller('userController', ['$scope', 'contextService', function ($scope, contextService) {
            var vm = this;
            vm.context = contextService.getContext();

            contextService.setContextValue("foo", "baz");
        }])
        .controller('customerController', ['$scope', 'contextService', function ($scope, contextService) {
            var vm = this;
            vm.context = contextService.getContext();

            vm.updateContext = function (key, value) {
                contextService.setContextValue(key, value);
            }
        }])

})();
<!DOCTYPE html>

<html lang="en" ng-app="app">
  <head>
    <meta charset="utf-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
    <script src="module.js"></script>
  </head>
  <body>
    <div ng-controller="userController as vm">
      <strong>userController</strong>
      <pre>
        foo = {{ vm.context.foo }}
        hello = {{ vm.context.hello }}
      </pre>
    </div>
    <hr />
    <div ng-controller="customerController as vm">
      <strong>customerController</strong>
      <pre>
        foo = {{ vm.context.foo }}
      </pre>
      <button ng-click="vm.updateContext('hello', 'guys')">
        Update context <strong>hello</strong> value
      </button>
    </div>
  </body>
</html>