何我可以從控制器調整大小的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