2017-05-30 58 views
0

我是angularjs的新手。我想以显示从一个控制器到另一个 这Ajax响应是控制器1将数据从一个控制器全局存储到另一个控制器使用服务

app.controller("currentTaskCtrl", function ($scope, $http, $rootScope, currentTaskService) { 

    $scope.currentTaskTab = function() { 
    $http({ 
      url: '/index/tasktimer', 
      method: 'POST',   
      data : {"currentTask": "current"}, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} 
     }).success(function(response) {     
       currentTaskService.saveData(response.task_name, response.estimated_hours, response.time_remaining, response.start_date, response.stop_date, response.actual_hours); 
      }).error(function(response) { 
       $scope.codeStatus = response || "Request failed" 
      });   
    }   
}); 

这是控制器2

app.controller("currentTaskTabCtrl", function ($scope, $rootScope, currentTaskService) { 

    $rootScope.$on('currentTaskService', function() { 
     $scope.data = currentTaskService.getData(); 
    }); 
}); 

这是服务

app.service('currentTaskService', function($rootScope) { 
    this.saveData = function(tname, estimated_hours, time_remaining, start_date, stop_date, actual_hours) { 
     // Here the data gets saved in $rootScope.data 
    } 

    this.getData = function() { 
     return data; 
    } 
}); 

这是HTML代码(控制器2)数据得到显示

<div ng-controller="currentTaskTabCtrl"> 
    <table> 
    <thead> 
     <tr> 
     <th> # </th> 
     <th> Task Name </th> 
     <th> Estimated Hours </th> 
     <th> Time Remaining </th> 
     <th> Start Date </th> 
     <th> Stop Date </th> 
     <th> Actual Time </th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr ng-repeat="task in data"> 
     <td></td> 
     <td>{{task.task_name}}</td> 
     <td>{{task.estimated_hours}}</td> 
     <td>{{task.time_remaining}}</td> 
     <td>{{task.start_date}}</td> 
     <td>{{task.stop_date}}</td> 
     <td>{{task.actual_time}}</td> 
     </tr> 
    </tbody> 
    </table> 
</div> 

回答

0

您可以按照:

1-注入$ rootScope到这两个控制器

2-实现下面的代码,其中一个作为数据接收器:

$rootScope.$on('transferDataEvent', function(event, data) { 
    // you will receive data here 
    }); 

3 - 并作为数据发送方拨打以下代码

$rootScope.$emit('transferDataEvent', data); // send data 

在 $使听者和 $发出向上调度该事件通过作用域层级

0

您可以从控制器发送数据为好。

<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,$rootScope) { 
     function sendData($scope) { 
      var arrayData = [1,2,3]; 
      $rootScope.$emit('someEvent', arrayData); 
     } 
    }); 
    app.controller('yourCtrl', function($scope, $http,$rootScope) { 
     $rootScope.$on('someEvent', function(event, data) { 
      console.log(data); 
     }); 
    }); 
</script> 
相关问题