gpt4 book ai didi

javascript - AngularJS '$watch' 值更改时未触发

转载 作者:行者123 更新时间:2023-11-29 19:18:33 25 4
gpt4 key购买 nike

我有一个必须以横向模式查看的网络应用。

为此,我创建了一个函数来检查 innerWidthinnderHeight , 如果宽度大于高度那么快乐的日子。这在我加载页面时非常有效,但我也可以在 resize 时检查方向事件被触发。

所以我的代码流程是——

  1. 触发 resize事件电话$scope.getOrienttion()
  2. 计算当前方向并返回结果
  3. 监控 $scope.getOrienttion() 值的变化使用 watch并更新 $scope.orientation 的值

上面的步骤 1 和 2 似乎工作正常,但我的 watch从不检测对 $scope.getOrienttion() 的更改并且仅在页面加载时触发。我一定是做错了什么,谁能帮我找出问题所在。

这是相关的 AngularJS -

christmasApp.controller('bodyCtrl', function($scope, $window){

angular.element($window).bind('resize', function(){
console.log('Event triggered');
$scope.getOrientation();
});

$scope.getOrientation = function(){

var w = $window.innerWidth,
h = $window.innerHeight;
var orientation = (w > h) ? 'landscape' : 'portrait'
console.log('Function triggered - ' + orientation)
return (w > h) ? 'landscape' : 'portrait';

};

$scope.$watch($scope.getOrientation, function(newValue, oldValue){
$scope.orientation = newValue;
console.log('Watch triggered - ' + newValue);
}, true);

});

这里是设置了条件类的 HTML,具体取决于 $scope.orientation 的值(可能不相关,但以防万一)-

<body <?php body_class(); ?> data-ng-controller="bodyCtrl">

<div id="orientationMask" data-ng-class="{visible: orientation != 'landscape'}">
<p>Please turn your device to the <b>landscape</b> orientation.</p>
</div>

{ Additional code, obscured by the mask if it is show... }

</body>

最佳答案

虽然从 resize 事件调用 getOrientation 只是执行 getOrientation 代码,但它并没有暗示某些东西发生了变化。因此,您需要通过 $scope 调用 $apply() 来告诉 Angular 运行摘要循环。在调用摘要循环之后,angular 将评估所有的 $watcher 并且你的 watcher 函数将被评估。

实际上,resize 事件中的 getOrientation 方法调用似乎没有做任何与范围级别绑定(bind)相关的事情。因此,您可以从那里删除 getOrientation 方法,因为它似乎调用了一个在那里什么都不做的代码。

代码

angular.element($window).bind('resize', function(){
console.log('Event triggered');
$scope.getOrientation(); //you could remove this method, as its not modifying any scope
//will run digest cycle, and the watcher expression will get evaluated
$scope.$apply(); //you could also use $timeout(function(){}) here run safe digest cycle.
});

关于javascript - AngularJS '$watch' 值更改时未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34107704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com