how to passing data from one controller to another controller using angular js 1

后端 未结 4 1906
予麋鹿
予麋鹿 2020-12-22 05:14

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this

4条回答
  •  旧时难觅i
    2020-12-22 06:02

    Sharing data from one controller to another using service

    We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.

    Service :

    app.service('setGetData', function() {
      var data = '';
        getData: function() { return data; },
        setData: function(requestData) { data = requestData; }
    });
    

    Controllers :

    app.controller('Controller1', ['setGetData',function(setGetData) {

    // To set the data from the one controller $scope.Message="Hi welcome";
    setGetData.setData($scope.Message);

    }]);

    app.controller('Controller2', ['setGetData',function(setGetData) {
    
      // To get the data from the another controller  
      var res = setGetData.getData();
      console.log(res); // Hi welcome
    
    }]);
    

    Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

提交回复
热议问题