2017-05-14 200 views
0

我有一個http請求控制器啓動控制器,我需要從另一個控制器調用它,這是我控制器需要啓動:從另一個角度控制器

app.controller('getDataCtrl', function ($scope, $http, $ionicLoading) { 
$scope.request = $http({ 
    method: "POST",   
    url: "someurl", 
    dataType: "json", 
    contentType: "application/json; charset=utf-8" 
}).then(function mySucces(response) { 
    $scope.allTracks = response.data; 
    $scope.recentTracks = response.data.Tracks; 
} 

,這是我如何試圖調用它:

angular.element(document.getElementById('getDataCtrl')).$scope.$apply(); 
+4

這是一個[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)和想法沒有任何意義。使用服務在整個應用程序中共享方法 – charlietfl

回答

1

您可以使用事件廣播控制器之間的通信:

angular.module('app', []); 
 

 
angular. 
 
module('app') 
 
    .controller('FirstController', ['$scope', '$rootScope', function($scope, $rootScope) { 
 
    $scope.test = function() { 
 
     // broadcast custom event with some data 
 
     // OR do something with a shared service 
 
     // 
 
     // SomeService.doSomething().then(function() { 
 
     // $rootScope.$broadcast("SOME_EVENT"); 
 
     // }); 
 
     // 
 
     $rootScope.$broadcast("SOME_EVENT", "someValue"); 
 
    }; 
 
    }]) 
 
    .controller('SecondController', ['$scope', '$rootScope', function($scope, $rootScope) { 
 
    // Listen for custom event 
 
    $rootScope.$on("SOME_EVENT", function(event, data) { 
 
     // Call controller function 
 
     $scope.updateData(data); 
 
    }) 
 
    // Do whatever you want here 
 
    $scope.updateData = function(data) { 
 
     // MyService.doSomethingElse().then(function() { 
 
     // ... 
 
     //}); 
 
     $scope.data = data; 
 
    } 
 
    }]);
<!doctype html> 
 

 
<html lang="en" ng-app="app"> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script> 
 
    <script src="script.js"></script> 
 
</head> 
 

 
<div ng-controller="FirstController"> 
 
    <button ng-click="test()">Test</button> 
 
</div> 
 
<div ng-controller="SecondController"> 
 
    <pre>{{ data }}</pre> 
 
</div> 
 

 
</html>

+0

@hhh是否有效? –

相關問題