gpt4 book ai didi

javascript - 从另一个 Controller 启动一个 Controller

转载 作者:行者123 更新时间:2023-12-03 04:20:39 27 4
gpt4 key购买 nike

我有一个带有http请求的 Controller ,我需要从另一个 Controller 调用它,这是我需要启动的 Controller :

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();

最佳答案

您可以使用事件广播在 Controller 之间进行通信:

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>

关于javascript - 从另一个 Controller 启动一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43963259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com