何我可以从控制器调整大小的angularJS窗口的宽度?我希望能够得到它,所以我可以显示一些div
与<div ng-if="windowWidth > 320">
如何从控制器调整angularJS中的窗口宽度?
我可以得到初始页面加载WINDOWWIDTH但不能调整...
'use strict';
var app = angular.module('app', []);
app.controller('mainController', ['$window', '$scope', function($window, $scope){
\t var mainCtrl = this;
\t mainCtrl.test = 'testing mainController';
// Method suggested in @Baconbeastnz's answer
$(window).resize(function() {
$scope.$apply(function() {
$scope.windowWidth = $(window).width();
});
});
/* this produces the following error
/* Uncaught TypeError: mainCtrl.$digest is not a function(…)
angular.element($window).bind('resize', function(){
mainCtrl.windowWidth = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
mainCtrl.$digest();
});
*/
}]);
// Trying Directive method as suggested in @Yaser Adel Mehraban answer.
/*app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E'
};
function link(scope, element, attrs){
angular.element($window).bind('resize', function(){
scope.windowWidth = $window.innerWidth;
});
}
}]);*/
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body ng-app="app" ng-controller="mainController as mainCtrl">
\t <p>{{mainCtrl.test}}</p>
\t <hr />
<p ng-if="windowWidth > 600">The window width is {{windowWidth}}</p>
<div my-directive ng-if="windowWidth > 320">It works!</div>
</body>
我在this answer中看到他们解释了如何从指令中获取它,但是如何从控制器内部使其工作?
只是想知道,岂不是更好地处理问题,调整使用CSS? – Harke