How to share the $scope variable of one controller with another in AngularJS?

前端 未结 3 1268
情话喂你
情话喂你 2020-12-05 17:51

I have this:

app.controller(\'foo1\', function ($scope) {
  $scope.bar = \'foo\';
});
app.controller(\'foo2\', function ($scope) {
  // want to access the $s         


        
3条回答
  •  我在风中等你
    2020-12-05 18:17

    You could use an Angular Service to share variable acrosss multiple controllers.

    angular.module('myApp', [])
    .service('User', function () {
        return {};
    })
    

    To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

    function ControllerA($scope, User) {
        $scope.user = User;
        $scope.user.firstname = "Vinoth";
    }
    
    function ControllerB($scope, User) {
        $scope.user = User;
        $scope.user.lastname = "Babu";        
    }
    

提交回复
热议问题