2015-02-11 55 views
0

我在寫一個控制器。該控制器必須與其他控制器通信。但我不知道它是否可行?如何在AngularJS中相互溝通控制器?

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

+0

可能重複(HTTP [什麼是在AngularJS控制器之間溝通的正確方法是什麼?]: //stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs) – 2015-02-11 08:39:45

回答

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/

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' 
    }); 
});