[英]AngularJS: Call controller update function from another controller or JS
I have a controller that updates a portion of the screen. 我有一个更新屏幕一部分的控制器。 Sometimes a user will do an action that will, on the server side, invalidate what that region shows. 有时,用户执行的操作将在服务器端使该区域显示的内容无效。 How then, when a user clicks a button elsewhere can I make another controller update? 然后,当用户单击其他位置的按钮时,如何进行另一个控制器更新? I have followed the usual pattern for such things ie : 我已经遵循了通常的模式,例如:
appControllers.controller('linksController', ['$scope', '$filter', '$interval', function ($scope, $filter, $interval) {
$scope.update = function () {
// update code here... this is what I want to invoke from another function or area of JS
}
You may to use shared service/factory for this. 您可以为此使用共享服务/工厂。
If you want to pass just loaded data from one controller to another, you can pass it through the "Shared Service" and broadcast event in it with $broadcast/$emit
functions. 如果要将刚加载的数据从一个控制器传递到另一个控制器,则可以通过$broadcast/$emit
shared $broadcast/$emit
函数通过“共享服务”传递它并在其中广播事件。 Broadcasted event can be listened in any controller with $scope.$on
. 广播事件可以在任何带有$scope.$on
控制器中收听。
angular.module("appControllers", []).factory("sharedService", function($rootScope){
var mySharedService = {};
mySharedService.values = {};
mySharedService.passData = function(newData){
mySharedService.values = newData;
$rootScope.$broadcast('dataPassed');
}
return mySharedService;
});
appControllers.controller('linksController', ['$scope', 'sharedService', function ($scope, sharedService) {
$scope.update = function(newData){
sharedService.passData(newData);
};
}
appControllers.controller('anotherController', ['$scope', 'sharedService', function ($scope, sharedService) {
$scope.$on('dataPassed', function () {
$scope.newItems = sharedService.values;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.