$ON和$广播(角)我有一个不同观点的页脚控制器和码扫描控制器。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中,我应该在codeScanerController中获取此事件。<li class="button" ng-click="startScanner()">3</li>我认为这是可以实现的$on和$broadcast,但我不知道怎么做,也不知道哪里都找不到例子。
3 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
$on(), $broadcast()$emit():
.$on(name, listener)-聆听某一特定事件 name.$broadcast(name, args)-通过 $scope在所有儿童中 .$emit(name, args)-向上发出一个事件 $scope所有父级的层次结构,包括 $rootScope
<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
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');
});}]);添加回答
举报
0/150
提交
取消
