我需要让 angularjs 文件中的一个 Controller 在同一 javascript 文件中的另一个 Controller 上调用刷新。
我已经在下面的代码集中创建了一个非常简化的版本。基本上,当我在下面的示例中单击按钮 1 时,我希望它调用 click1 函数,然后让 click1 函数调用第二个 Controller 上的 click2 函数。当您点击第二个 Controller 中的 click2 函数时,情况正好相反。
HTML
<div ng-app>
<div ng-controller="Control1">
<div>{{count1}}</div>
<button ng-click="click1()">Call both click methods from controller 1</button>
</div>
<div ng-controller="Control2">
<div>{{count2}}</div>
<button ng-click="click2()">Call both click methods from controller 2</button>
</div>
</div>
Javascript
function Control1($scope) {
$scope.count1 = 0;
$scope.click1 = function () {
$scope.count1++;
}
}
function Control2($scope) {
$scope.count2 = 0;
$scope.click2 = function () {
$scope.count2 = $scope.count2 + 2;
}
}
我还创建了一个 jsfiddle为此。
最佳答案
你将不得不使用范围广播或发射...类似
function Control1($scope, $rootScope) {
$scope.count1 = 0;
$scope.$on('clicked2', function() {
$scope.count1++;
});
$scope.click1 = function () {
$scope.count1++;
$rootScope.$broadcast('clicked1');
}
}
function Control2($scope, $rootScope) {
$scope.count2 = 0;
$scope.$on('clicked1', function() {
$scope.count2 = $scope.count2 + 2;
})
$scope.click2 = function () {
$scope.count2 = $scope.count2 + 2;
$rootScope.$broadcast('clicked2');
}
}
http://jsfiddle.net/jX3kh/ 在这里阅读更多信息 http://docs.angularjs.org/api/ng.$rootScope.Scope#methods_$broadcast .
关于javascript - 从另一个 Controller 调用 Controller 中的一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21149589/