AngularJS $watch window resize inside directive

前端 未结 3 1306
借酒劲吻你
借酒劲吻你 2020-12-02 15:33

I have revealing module pattern which looks like this:

\'use strict\';

angular.module(\'app\', [])
   .directive(\'myDirective\', [\'SomeDep\', function (So         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 15:53

    You shouldn't need a $watch. Just bind to resize event on window:

    DEMO

    'use strict';
    
    var app = angular.module('plunker', []);
    
    app.directive('myDirective', ['$window', function ($window) {
    
         return {
            link: link,
            restrict: 'E',
            template: '
    window size: {{width}}px
    ' }; 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(); }); } }]);

提交回复
热议问题