각도로 $on 및 $120
뷰가 다른 footerController와 codeScannerController가 있습니다.
angular.module('myApp').controller('footerController', ["$scope", function($scope) {}]);
angular.module('myApp').controller('codeScannerController', ["$scope", function($scope) {
console.log("start");
$scope.startScanner = function(){...
를 클릭하면<li>
footer.html에서 이 이벤트를 codeScannerController로 가져옵니다.
<li class="button" ng-click="startScanner()">3</li>
제 생각에 그것은 다음과 같이 실현될 수 있을 것 같습니다.$on
그리고.$broadcast
어디서도 예를 찾을 수 없고 또 찾을 수 없습니다.
원하신다면$broadcast
를 사용하다$rootScope
:
$scope.startScanner = function() {
$rootScope.$broadcast('scanner-started');
}
그 후 수신하려면 ,$scope
사용 중인 컨트롤러:
$scope.$on('scanner-started', function(event, args) {
// do what you want to do
});
원하는 경우 인수 전달이 가능합니다.$broadcast
:
$rootScope.$broadcast('scanner-started', { any: {} });
그런 다음 수신:
$scope.$on('scanner-started', function(event, args) {
var anyThing = args.any;
// do what you want to do
});
이것에 대한 설명서는, 스코프 문서에 기재되어 있습니다.
.$on(name, listener)
- 특정 이벤트를 특정별로 청취합니다.name
.$broadcast(name, args)
- 이벤트를 브로드캐스트합니다.$scope
하필이면.$emit(name, args)
- 위쪽으로 이벤트를 내보냅니다.$scope
모든 부모에 대한 위계질서,$rootScope
다음 HTML을 기반으로 합니다(여기서 전체 예 참조).
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
기동된 이벤트는, 다음과 같이 행해집니다.$scopes
다음과 같습니다.
- 브로드캐스트 1 - 컨트롤러 1에서만 표시됨
$scope
- 발광 1 - 컨트롤러 1에서 인식됩니다.
$scope
그리고나서$rootScope
- 브로드캐스트 2 - 컨트롤러 2에서 표시됨
$scope
그 후 컨트롤러 3$scope
- 출력 2 - 컨트롤러 2에서 인식됩니다.
$scope
그리고나서$rootScope
- 브로드캐스트 3 - 컨트롤러 3에서만 표시됨
$scope
- 출력 3 - 컨트롤러 3에서 인식됩니다.
$scope
, 컨트롤러 2$scope
그리고나서$rootScope
- 브로드캐스트 루트 - 다음에 표시됩니다.
$rootScope
그리고.$scope
모든 컨트롤러 (1, 2, 3) - 루트 내보내기 - 다음 사용자만 볼 수 있습니다.
$rootScope
이벤트를 트리거하는 JavaScript(여기에서도 작업 예를 볼 수 있습니다):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);
$ prefix는 Angular Method를 나타내고 $$ prefix는 사용을 피해야 하는 Angular Method를 나타냅니다.
템플릿과 그 컨트롤러의 예를 다음에 나타냅니다.$140/$on이 우리가 원하는 것을 달성하는 데 어떻게 도움이 되는지 알아보겠습니다.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
컨트롤러는
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
궁금한 점은 사용자가 register를 클릭했을 때 두 번째 컨트롤러에 이름을 전달하려면 어떻게 해야 합니까?여러 가지 솔루션을 제안할 수도 있지만, 저희가 사용하는 솔루션은 $broadcast와 $on을 사용하는 것입니다.
193달러 vs 195달러
어떤 걸로 할까요?$dom은 모든 자식 돔 요소에 채널 다운되고 $dom은 모든 조상 돔 요소에 반대 방향으로 채널 다운됩니다.
$emit과 $broadcast 중 하나를 선택하지 않는 가장 좋은 방법은 $rootScope에서 채널을 돌려 $broadcast를 모든 자녀에게 사용하는 것입니다.우리 돔 요소들이 형제자매이기 때문에 우리 사건이 훨씬 수월해 졌지.
$rootScope 및 $broadcast 추가
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
$rootScope를 추가하여 $broadcast(broadcastName, 인수)를 사용하고 있습니다.broadcastName의 경우 고유한 이름을 지정하여 두 번째 Ctrl에서 해당 이름을 사용할 수 있도록 합니다.BOOM! 그냥 재미로 골랐어요.두 번째 인수 'arguments'는 청취자에게 값을 전달할 수 있도록 합니다.
저희 방송 수신
두 번째 컨트롤러에서는 방송을 듣기 위한 코드를 설정해야 합니다.
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
그건 정말 간단해.라이브 예시
유사한 결과를 얻기 위한 기타 방법
이 방법은 효과적이지도 않고 유지보수가 용이하지도 않지만 문제를 해결하는 간단한 방법이므로 사용하지 않도록 하십시오.
일반적으로 서비스를 사용하거나 컨트롤러를 단순화하는 방법으로 동일한 작업을 수행할 수 있습니다.자세한 내용은 설명하지 않겠습니다만, 조금 더 자세히 말씀드리려고 합니다.
마지막으로 정말 유용한 브로드캐스트는 '$destroy'입니다.$는 벤더 코드에 의해 작성된 메서드 또는 오브젝트임을 알 수 있습니다.어쨌든 컨트롤러가 파괴되면 $destroy가 브로드캐스트되므로 컨트롤러가 언제 분리되었는지 이 내용을 들어보면 알 수 있습니다.
//Your broadcast in service
(function () {
angular.module('appModule').factory('AppService', function ($rootScope, $timeout) {
function refreshData() {
$timeout(function() {
$rootScope.$broadcast('refreshData');
}, 0, true);
}
return {
RefreshData: refreshData
};
}); }());
//Controller Implementation
(function () {
angular.module('appModule').controller('AppController', function ($rootScope, $scope, $timeout, AppService) {
//Removes Listeners before adding them
//This line will solve the problem for multiple broadcast call
$scope.$$listeners['refreshData'] = [];
$scope.$on('refreshData', function() {
$scope.showData();
});
$scope.onSaveDataComplete = function() {
AppService.RefreshData();
};
}); }());
언급URL : https://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular
'it-source' 카테고리의 다른 글
JPA 및 휴지 상태 사용 시 ID 생성 전략을 선택하는 방법 (0) | 2023.01.03 |
---|---|
Conda를 사용하여 Python 3.6으로 업그레이드하려면 어떻게 해야 하나요? (0) | 2023.01.03 |
to_sql 및 sqlalchemy를 사용한 mariadb 데이터베이스로의 panda 데이터 프레임 (0) | 2022.12.29 |
"액티비티로 인해 페이지가 만료되었습니다." - Larabel 5.5 (0) | 2022.12.29 |
Mysql 서비스가 없습니다. (0) | 2022.12.29 |