我想设置$ scope.columns取决于窗口大小。如果语句运行良好,但在$ window函数中我无权访问范围变量。我该怎么办?
.controller("mainController", function($window, $scope) {
$window.onresize = function() {
var screenWidth = $window.innerWidth;
if (screenWidth < 1285) {
$scope.columns = 1;
} else if (1767 > screenWidth && screenWidth >= 1285) {
$scope.columns = 2;
} else if (2249 > screenWidth && screenWidth >= 1767) {
$scope.columns = 3;
} else if (2731 > screenWidth && screenWidth >= 2249) {
$scope.columns = 4;
} else if (3213 > screenWidth && screenWidth >= 2249) {
$scope.columns = 5;
} else if (screenWidth >= 3213) {
$scope.columns = 6;
}
}
})
答案 0 :(得分:2)
您绝对可以访问$scope
个变量。问题是$window.onresize
事件不受角度监督,因此进行了更改,但在下一个摘要之前,未在UI上反映出来。您必须通知角度$scope.$apply()
所做的更改。试试这个:
.controller("mainController", function($window, $scope) {
$window.onresize = function() {
$scope.$apply(function() {
var screenWidth = $window.innerWidth;
if (screenWidth < 1285) {
$scope.columns = 1;
} else if (1767 > screenWidth && screenWidth >= 1285) {
$scope.columns = 2;
} else if (2249 > screenWidth && screenWidth >= 1767) {
$scope.columns = 3;
} else if (2731 > screenWidth && screenWidth >= 2249) {
$scope.columns = 4;
} else if (3213 > screenWidth && screenWidth >= 2249) {
$scope.columns = 5;
} else if (screenWidth >= 3213) {
$scope.columns = 6;
}
});
}
})
答案 1 :(得分:1)
我相信当事件触发时,该函数将在窗口范围内执行,您可以尝试将范围设置为控制器属性,并将该函数绑定到控制器:
.controller("mainController", function($window, $scope) {
this.scope = $scope;
$window.onresize = function() {
var screenWidth = $window.innerWidth;
if (screenWidth < 1285) {
this.scope.columns = 1;
} else if (1767 > screenWidth && screenWidth >= 1285) {
this.scope.columns = 2;
} else if (2249 > screenWidth && screenWidth >= 1767) {
this.scope.columns = 3;
} else if (2731 > screenWidth && screenWidth >= 2249) {
this.scope.columns = 4;
} else if (3213 > screenWidth && screenWidth >= 2249) {
this.scope.columns = 5;
} else if (screenWidth >= 3213) {
this.scope.columns = 6;
}
}.bind(this);
})