我已经阅读了类似的问题,我无法理解为什么这不会更新。我可以在catch事件中获取范围变量更新的日志。但它没有更新视图。所以它填充了“test”,但是在更新$ scope.keyPressed时不会更新。
指令
app.directive('keypressEvents', [
'$document',
'$rootScope',
function($document, $rootScope) {
return {
restrict: 'A',
link: function() {
$document.bind('keypress', function(e) {
console.log('Got keypress:', e.which);
// console.log('document', $document)
$rootScope.$broadcast('keypress', e);
$rootScope.$broadcast('keypress:' + e.which, e);
});
}
};
}
]);
控制器
$scope.keyPressed = 'test';
$scope.$on('keypress:13', function(onEvent, keypressEvent) {
$scope.keyPressed = 'Enter';
console.log($scope.keyPressed);
});
// For listening to all keypress events
$scope.$on('keypress', function(onEvent, keypressEvent) {
if (keypressEvent.which === 120) {
$scope.keyPressed = 'x';
}
else {
console.log('else' ,keypressEvent);
$scope.keyPressed = 'Keycode: ' + keypressEvent.which;
}
});
视图
<div data-keypress-events>
{{keyPressed}}
</div>
视图的控制器在加载部分时由路由提供者指定。
.when('/feed/:url', {
templateUrl: '/templates/eventWall-feed',
controller: 'eventWallFeedController'
})
答案 0 :(得分:4)
$on
和$broadcast
不会致电$apply
,因此您需要将$scope.keypPressed
包裹在$apply
之内
$scope.$apply(function() {
$scope.keyPressed = 'x';
});
答案 1 :(得分:1)
您可以尝试在按键功能的末尾添加$ scope。$ apply()。