如何将值传递给Angular js中的不同控制器

[英]How do I pass value to different controller in Angular js


I am using angular framework and trying to pass $scope to different controller in my app.

我正在使用角度框架并尝试将$ scope传递给我的应用程序中的不同控制器。

UPDATE:

更新:

My problem is I wan't obtain the $scope data until user click a button.

我的问题是,在用户点击按钮之前,我不会获取$ scope数据。

.controller('firstCtrl', function($scope) {
    $scope.getTest = function(){
        $scope.test1 = 'good.'
        $scope.test2 = 'bad.'
        …..more
   }
})

I need to pass $scope object to different controller

我需要将$ scope对象传递给不同的控制器

.controller('secondCtrl', function($scope) {
    console.log($scope.test1)
})

How do I do it? Thanks!

我该怎么做?谢谢!

3 个解决方案

#1


1  

Use custom events on the $rootScope

在$ rootScope上使用自定义事件

.controller('firstCtrl',['$rootScope', function($rootScope) {
    $scope.getTest = function(){
        $rootScope.your_object = {foo:bar}
        $rootScope.$emit('custom_event');
   }
}])

.controller('secondCtrl', function($scope,$rootScope) {
    $rootScope.$on('custom_event',function(){
    //do stuff
    //$rootScope.your_object is available
    })

});

You may need to unbind the root scope from that event if the controllers instantiate more then once

如果控制器实例化多次,则可能需要从该事件解除绑定根范围

There may be an objection against 'polluting' the root scope but that's what its there for.

可能存在反对“污染”根范围的反对意见,但这就是它的用途。

#2


2  

In order to share data between two controllers you need to use factory.

要在两个控制器之间共享数据,您需要使用工厂。

For more details, please watch this video: "AngularJS Video Tutorial: Sharing Data Between Controllers" by John Lindquist.

有关详细信息,请观看此视频:John Lindquist撰写的“AngularJS视频教程:控制器之间共享数据”。

#3


2  

To share information between controllers, you use services. A service can be created like this:

要在控制器之间共享信息,请使用服务。可以像这样创建服务:

//Create angular main app module
var app = angular.module('myApp', []);

//create a service
app.service('sharedService', function () {
    this.test1 = [1, 2, 3, 4];
});

//one controller, injecting the service
app.controller('firstCtrl', function ($scope, sharedService) {
    sharedService.test1[0] = 5;
    console.log(sharedService.test1[0]) //5, 2, 3, 1
});

//two controller, injecting the same service
app.controller('secondCtrl', function ($scope, sharedService) {
    sharedService.test[1] = 4;
    console.log(sharedService.test1[0]) //5, 4, 3, 1
});

Here is an example I just created on jsFiddle:

这是我刚刚在jsFiddle上创建的一个例子:

http://jsfiddle.net/NHtFu/

http://jsfiddle.net/NHtFu/

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2014/03/27/82bfbac4e2a6d6f1c065dd19c0df50d.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告