从另一个控制器角度启动控制器

时间:2017-05-14 11:17:45

标签: javascript angularjs controller

我有一个带有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();

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;