How to transfer the data between controllers

2019-01-20 16:17发布

问题:

I tought angular and faced with a problem: I have a SPA which contains two parts with controllers, the data returns from json file. The first conroller for showing the menu, the second - for adding a new item. For now in json file there are two object, but when I added a third item in the second controller, It dissapeared when I return on the first page. How can I fix it? I've read that factory can transfer the data between controllers, but I've never use It.

Angular module:

var myApp = angular.module("testModule", ['ngRoute']);

myApp.config(function ($routeProvider){
    $routeProvider.when('/', {
        templateUrl: 'pages/main.html',
        controller: 'mainCtrl'
    })
    .when('/add', {
        templateUrl: 'pages/add.html',
        controller: 'addCtrl'
    })
})



myApp.controller("mainCtrl", function ($scope, $http) {
            $http.get("model/data.json").success(function (response) {
                $scope.list = response;
            })                  

    });

myApp.controller("addCtrl", function ($scope, $http) {

            $scope.addAdv = function(newAdv){
                $http.get("model/data.json").success(function (response) {
                    response.push({
                        name: newAdv.name,
                        shop: newAdv.shop 
                    });
            })
        }; 
    });

JSON file:

[{
    "name": "New Item",
    "shop": "Titan"
},
{
    "name": "New Item1",
    "shop": "Titan"
}]

回答1:

You can use angular services to share data between your controllers. you should first create service for getting information form your server

var app = angular.module('app', ['ngRoute']);
app.service('dataService', function($http) {
  var data = {};
    data.list = [];
  var getData = function(){
    $http.get("model/data.json").then(function (response) {
      data.list = response.data;
    },function(err){});

  }
    return {
        getDataFromServer:getData,
        getData:data,

    }
});

Now you can use this service in your controller:

app.controller("mainCtrl", function ($scope, dataService) {
       dataService.getDataFromServer();      

});

app.controller("addCtrl", function ($scope, dataService) {
    $scope.data = dataService.getData;
    $scope.data.list.push({
        name:"foo",
        shop:"bar"
    });
});

And here is jsfiddle code: https://jsfiddle.net/xqn5yu8g/

For more information about angular services take look at angularjs services document page



回答2:

As Daniel.v said, a service is the best way. There are also two less elegant alternatives:

  • "if data is owned by two controllers, these should share a $parent, and It should be the owner of data!"
  • "hey, why don't we use events and listeners? Let's go for $broadcast and $emit!"

But i mainly prefer services.



回答3:

  1. use service
  2. user $broadcast or $emit
  3. use $rootScope (not recommended)


回答4:

This will work for you :

`

<div ng-app="myApp" ng-controller="myCtrl"> 

    <button ng-click="sendData();"></button>

</div>


<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        function sendData($scope) {
            var arrayData = [1,2,3];
            $scope.$emit('someEvent', arrayData);
        }

    });
    app.controller('yourCtrl', function($scope, $http) {
        $scope.$on('someEvent', function(event, data) {
            console.log(data); 
        }); 
    });
</script>

`