angularjs - 如何从不同的控制器调用另一个控制器的功能
问题描述
我使用 angular js 作为我的客户端。我想调用另一个控制器中的一个函数。我怎样才能做到这一点?
解决方案
var app = angular.module('MyApplication', []);
app.controller('Controller1', function($scope, $rootScope) {
$scope.function1 = function() {
console.log('Controller 1 clicked and Function 1 called');
}
//receive the fuction using $on MyFunction
$rootScope.$on("CallController1", function() {
console.log('Controller 2 clicked and Controller 1 called');
});
});
app.controller('Controller2', function($scope) {
$scope.function2 = function() {
console.log('Controller 2 clicked and Function 2 called');
$scope.$emit("CallController1"); //emit the fuction using MyFunction
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyApplication">
<div ng-controller="Controller1">
<button ng-click="function1()">function 1</button>
</div>
<br>
<div ng-controller="Controller2">
<button ng-click="function2()">function 2</button>
</div>
</div>
推荐阅读
- c++ - 指定针对具有相同名称的不同函数的类内使用声明
- node.js - 直接将 Google Cloud Speech API 与 Angular 7 集成
- java - 如何在 Spring Boot 中使用明确指定的编组器
- vaadin - Vaadin 8 TwinColSelect 组件不在中心
- android - 只有创建视图层次结构的原始线程才能接触其视图。更新然后崩溃
- reactjs - React App 链接中的错误无法正常工作
- html - 无法在角度组件中为 ngFor 获取对象
- makefile - makefile 先决条件列表中的分号是什么?
- javascript - ngrx/store-angular - 状态不保留一些数据
- javascript - 跨组件发送多个道具 React