Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $watch仅在第一次更新window.innerWidth时激发_Javascript_Angularjs - Fatal编程技术网

Javascript $watch仅在第一次更新window.innerWidth时激发

Javascript $watch仅在第一次更新window.innerWidth时激发,javascript,angularjs,Javascript,Angularjs,我正在尝试设置我的应用程序以查看窗口。innerWidth属性并根据该宽度向$scope添加属性。它第一次起作用,但之后的任何调整都不起作用。是否未调用$digest方法?如果是,为什么不呢 模块 //Initialize angular module include route dependencies var app = angular.module("selfservice", ['ngRoute']); app.config(function ($routeProvider) {

我正在尝试设置我的应用程序以查看
窗口。innerWidth
属性并根据该宽度向
$scope
添加属性。它第一次起作用,但之后的任何调整都不起作用。是否未调用$digest方法?如果是,为什么不呢

模块

//Initialize angular module include route dependencies

var app = angular.module("selfservice", ['ngRoute']);

app.config(function ($routeProvider) {
   $routeProvider
       .when('/', {
           templateUrl:"partials/login.html",
           controller:"login"
       });
});
控制器

app.controller("login", ['$scope', function ($scope) {


$scope.$watch(

    function () {
        return window.innerWidth;
    },

    function (newval, oldval) {
        if (newval < 700) {
            $scope.classExpand = 'expand';
        } else {
            $scope.classExpand = '';
        }

        console.log(newval, oldval);
    });



}]);
app.controller(“登录”、['$scope',函数($scope){
$scope.$watch(
函数(){
返回窗口.innerWidth;
},
函数(newval、oldval){
如果(新值<700){
$scope.classExpand='expand';
}否则{
$scope.classExpand='';
}
console.log(newval、oldval);
});
}]);
看法



这是第一次工作,如果我在调整大小后刷新屏幕,会应用expand类,但是当我调整大小时,什么也不会发生,console.log函数甚至不会启动调整窗口大小不会导致Angle重新运行
$digest
循环,因此,只有在其他原因导致时才会检查
window.innerWidth
的值

您应该改为使用指令(即,不要在控制器中执行此操作),绑定到
窗口。onresize
事件:

.directive('watchResize', function(){
  return {
    restrict: 'A',
    link: function(scope, elem, attr) {
      angular.element(window).on('resize', function(){
        scope.$apply(function(){
          scope.classExpand = (window.innerWidth < 700) ? 'expand' : '';
        });
      });
    }
  }
});

(全屏观看效果最佳)

有没有理由不绑定到
窗口。onresize
事件(浏览器本机启动)而不是使用
$watch
,它只会在Angular的日程表上启动?没有,我想没有,这只是我第一次想到的方法,我不确定为什么它不起作用。虽然这可能是最好的方式,但我仍然很好奇为什么$watch没有像它应该的那样开火
.directive('watchResize', function(){
  return {
    restrict: 'A',
    link: function(scope, elem, attr) {
      angular.element(window).on('resize', function(){
        scope.$apply(function(){
          scope.classExpand = (window.innerWidth < 700) ? 'expand' : '';
        });
      });
    }
  }
});
<div watch-resize>
  {{ classExpand }}
</div>