0

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

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 上修复了示例:示例

4

2 回答 2

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'
   });
});
于 2015-02-11T08:40:06.727 回答
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/

于 2015-02-11T08:44:53.640 回答