如何在AngularJS中相互通信控制器?

时间:2015-02-11 08:31:36

标签: javascript angularjs angularjs-scope rootscope

我正在写一个控制器。该控制器必须与其他控制器通信。但我不知道它是否可行?

HTML:

<div data-ng-app="TestApp">
<div data-ng-controller="menuCtrl">
    <ul>
        <li> <a data-ng-click="Click()">
            Menü1</a>
        </li>
    </ul>
</div>
<div data-ng-controller="pageCtrl">
    <hr/> 
    <button data-ng-click="getText()">GetText</button>
    <br/>
    <strong data-ng-model="boldText"> {{boldText}}</strong>
</div>

JS:

var app = angular.module('TestApp', []);

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
    //???
    };
})
.controller('pageCtrl', function ($rootScope, $scope) {

    $scope.getText = function () {
        $scope.boldText = 'tst';
    };
});

我修复了JSfiddle上的示例:sample

2 个答案:

答案 0 :(得分:1)

您可以通过广播轻松实现这一目标:

var app = angular.module('TestApp', []);

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
        $scope.$broadcast('MyClickEvent', {
           someProp: 'Clicking data!' // send whatever you want
        });

    };
})

.controller('pageCtrl', function ($rootScope, $scope) {

   $scope.getText = function () {
       $scope.boldText = 'tst';
   };
   $scope.$on('MyClickEvent', function (event, data) {
        console.log(data); // 'Data to send'
   });
});

答案 1 :(得分:0)

使用广播事件,我们可以将值从一个控制器传递到另一个控制器

app.controller('menuCtrl', function ($rootScope, $scope) {
    $scope.Click = function () {
        var valueToPass = "value";
        $rootScope.$broadcast('eventMenuCtrl', valueToPass);
    };
})
.controller('pageCtrl', function ($rootScope, $scope) {

    $scope.getText = function () {
        $scope.boldText = 'tst';
    };

    $scope.$on('eventMenuCtrl', function(event, value) {
        $scope.boldText = value;
    })
});

http://jsfiddle.net/q2yn9jqv/4/