简体   繁体   中英

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.

UPDATE:

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

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

I need to pass $scope object to different controller

.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 .

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

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:

http://jsfiddle.net/NHtFu/

Use custom events on the $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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