简体   繁体   English

如何将值传递给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! 谢谢!

In order to share data between two controllers you need to use factory . 为了在两个控制器之间共享数据,您需要使用factory

For more details, please watch this video: " AngularJS Video Tutorial: Sharing Data Between Controllers " by John Lindquist. 有关更多详细信息,请观看此视频:John Lindquist撰写的“ AngularJS视频教程: 在控制器之间共享数据 ”。

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/

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. 可能存在反对“污染”根范围的异议,但这正是其目的所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM