AngularJS $ watch窗口调整内部指令

我有揭示模块模式,看起来像这样:

'use strict'; angular.module('app', []) .directive('myDirective', ['SomeDep', function (SomeDep) { var linker = function (scope, element, attr) { // some work }; return { link: linker, restrict: 'E' }; }]) ; 

我遇到麻烦的是将$ watch整合到此。 特别注意窗口大小,用“$ window”服务。

[编辑]:

我意识到我的问题是这一整个时间…我限制元素,当我忘了我正在实现它作为属性… @ _ @;

你不应该需要一个$手表。 只需绑定到调整窗口上的事件:

DEMO

 'use strict'; var app = angular.module('plunker', []); app.directive('myDirective', ['$window', function ($window) { return { link: link, restrict: 'E', template: '<div>window size: {{width}}px</div>' }; function link(scope, element, attrs){ scope.width = $window.innerWidth; angular.element($window).bind('resize', function(){ scope.width = $window.innerWidth; // manuall $digest required as resize event // is outside of angular scope.$digest(); }); } }]); 

您可以聆听resize事件,并在有些尺寸发生变化时触发

指示

 (function() { 'use strict'; angular .module('myApp.directives') .directive('resize', ['$window', function ($window) { return { link: link, restrict: 'A' }; function link(scope, element, attrs){ scope.width = $window.innerWidth; function onResize(){ // uncomment for only fire when $window.innerWidth change // if (scope.width !== $window.innerWidth) { scope.width = $window.innerWidth; scope.$digest(); } }; function cleanUp() { angular.element($window).off('resize', onResize); } angular.element($window).on('resize', onResize); scope.$on('$destroy', cleanUp); } }]); })(); 

在html中

 <div class="row" resize> , <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> <h4 ng-bind="::v.known_as"></h4> </div> </div> 

控制器:

 $scope.$watch('width', function(old, newv){ console.log(old, newv); }) 

/ /以下是窗口重新大小的angular度2.0指令,调整滚动条为您的标记赋予元素

 ---- angular 2.0 window resize directive. import { Directive, ElementRef} from 'angular2/core'; @Directive({ selector: '[resize]', host: { '(window:resize)': 'onResize()' } // Window resize listener }) export class AutoResize { element: ElementRef; // Element that associated to attribute. $window: any; constructor(_element: ElementRef) { this.element = _element; // Get instance of DOM window. this.$window = angular.element(window); this.onResize(); } // Adjust height of element. onResize() { $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px'); } }