2014-06-05 188 views
0

我试图通过使用State Provider将数据传递到我的控制器。如何将数据从一个控制器传递到另一个控制器

我有这样的事情

app.js

$stateProvider  
     .state('test', { 
      url: '/te', 
      views: { 
       '': { 
        templateUrl: 'test.html', 
        controller: 'testCtrl' 
       }, 
       data:{ 
        testValue:true 
       } 
      } 
     }) 

我的控制器:

app.controller('mainTestCtrl', function($scope) { 
    //I need to be able to get the testValue from here. 
}) 


app.controller('testCtrl', function($scope, $state) { 
    var testValue = $state.current.views.data.testValue; 
}) 

我真的不能提供mainTestCtrl国家提供,因为我需要测试值是true只有当调用testCtrl时。我需要一种方法将testValue传递给mainTestCtrl。有没有办法做到这一点?谢谢。

+0

在其中'testCtrl'被实例化的一点,就是' mainTestCtrl'已经实例化自己? –

+0

@Marc yes mainTestCtrl将在testCtrl之前实例化 – FlyingCat

回答

0

如果两个控制器的级别相同(a.e不是父母子女),则可以使用$rootScope.$broadcast

演示1 Fiddle

当心!

确保2 第二控制器初始化发送$broadcast之前。否则,没有人会听。


但我会用服务,将存储testValue和每个控制器可以把它抓回来:

演示2 Fiddle

+0

为什么父子关系排除使用'$ rootScope。$ broadcast'? –

+0

@MarcKline对我来说,在$ rootScope下面经常使用'。$ broadcast'是不太好的风格。如果是父母子女,父母通过使用他自己的范围发送广播,但不是'$ rootScope' –

+0

我看到...我以为你在说这是不可能的(我会反对)。我想你只是说你不会推荐它。 –

相关问题