2014-11-25 43 views
0

我是ng的新手。在這裏,我有一個場景,我需要從其他控制器收到成功的響應。我已經嘗試了下面的代碼,但我無法實現我的目標。如何從一個ng控制器到另一個控制器採用這個resposne

CODE:

  $scope.received = function(){ 

       $http({ 
        url : "/generic/getdata", 
        method : 'GET', 
        }).success(function(data) { 
        //The data received here I need t take to mydataController 
        $location.path('/success'); 

       }) 

       when('/success', { 
       templateUrl: 'ngtemplates/success/success.html', 
       controller: 'mydataController' 
       }). 
     app.controller('mydataController', 
    [ '$scope', '$http',function($scope, $http,$location) { 
      //I want the success data here in some function 
      }]); 

請幫我

回答

0

你可以使用的服務爲您的目的。

服務:

myApp.factory('dataService', function() { 

var _data; 

this.setData = function(someData) { 
_data = someData; // better use angular.copy() function 
} 

return { 
    data : _data; 
    } 
}); 

HTTP CALL:

$http({ 
url : "/generic/getdata", 
method : 'GET', 
}).success(function(data) { 
//The data received here I need t take to mydataController 

// before using dataService, make sure you inject it to the controller 
dataService.setData(data); 

$location.path('/success'); 

}); 

控制器

app.controller('mydataController', 
    [ '$scope', '$http',function($scope, $http,$location, dataService) { 
      //I want the success data here in some function 

     var someData = dataService.data; 
    }]); 
0

你有2秒olutions。您可以提供服務或使用活動。

$http({ 
    url : "/generic/getdata", 
    method : 'GET', 
    }).success(function(data) { 
    $rootScope.$broadcast('dataReceived', data); 
    $location.path('/success'); 
}); 

在mydataController:

$rootScope.$on('dataReceived', function(e, data) { 
// do something with the data 
} 

或者你可以做一個服務共享兩者之間的數據。

$http({ 
     url : "/generic/getdata", 
     method : 'GET', 
     }).success(function(data) { 
     myDataService.setData(data); 
     $location.path('/success'); 
    }); 

在mydataController:

$scope.something = myDataService.data; 

angular.module('demo').service('myDataService', function() { 

this.data = null; 

this.setData = function(data) { 
this.data = data; 
} 

}); 
在控制器

相關問題