如何将一些数据从一个控制器传递到另一个控制器

29 angularjs

我有以下两个对等控制器.这些没有父母:

<div data-ng-controller="Controller1">

</div>

<div data-ng-controller="Controller2">
   The value of xxx is: {{ xxx }}
</div>

angular.module('test')
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope'
    function ($rootScope, $scope) {
    // How can I set the value of xxx in the HTML that's part of Controller2    
    }]);

angular.module('test')
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope',
    function ($rootScope, $scope) {
    }]);
Run Code Online (Sandbox Code Playgroud)

在控制器1中,我想更新由Controller2控制的HTML中的变量xxx的值.有没有办法可以做到这一点?

kmd*_*sax 39

使用服务来实现这一目标:

MyApp.app.service("xxxSvc", function () {

var _xxx = {};

return {
    getXxx: function () {
        return _xxx;
    },
    setXxx: function (value) {
        _xxx = value;
    }
};

});
Run Code Online (Sandbox Code Playgroud)

接下来,将此服务注入两个控制器.

在Controller1中,您需要通过调用服务来设置共享xxx值: xxxSvc.setXxx(xxx)

最后,在Controller2中,在此服务的getXxx()函数上添加$ watch,如下所示:

  $scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
        if (newValue != null) {
            //update Controller2's xxx value
            $scope.xxx= newValue;
        }
    }, true);
Run Code Online (Sandbox Code Playgroud)

  • 这可以作为工厂吗? (2认同)

Cra*_*ire 22

绝对使用服务在控制器之间共享数据,这是一个工作示例.$ broadcast不是要走的路,你应该避免在有更合适的方式时使用事件系统.使用'service','value'或'constant'(对于全局常量).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

下面是一个输入示例,您可以在页面上看到数据镜像:http: //plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    });
Run Code Online (Sandbox Code Playgroud)

  • 但这不是对服务进行两次单独调用吗?我的意思是,如果服务是一个http请求,它不会为相同的数据创建两个单独的http请求吗? (2认同)

Jim*_*ote 16

在一个控制器中,您可以:

$rootScope.$broadcast('eventName', data);
Run Code Online (Sandbox Code Playgroud)

并在另一个地方听取这个事件:

$scope.$on('eventName', function (event, data) {...});
Run Code Online (Sandbox Code Playgroud)