Angular $ watch不响应窗口大小调整

时间:2014-07-31 18:41:43

标签: javascript angularjs

我在window.innerHeight和window.innerWidth上设置了一个带有$ watch的Angular应用程序来调整自动截断长度变量。它在我最初加载或重新加载页面时有效,但在页面调整大小时无效。有人可以帮忙吗?

这是我的模板:

<body class="partner_widget" ng-app="PartnerWidgetApp">
  <div id="description" ng-controller="PartnerWidgetController" ng-init="description='<%= expert_description %>'">
    {{ description_text | cut:true:blurb_truncate_length:'...' }}
  </div>
</body>

这是我的角色代码:

var PartnerWidgetApp = angular.module('PartnerWidgetApp', []);

PartnerWidgetApp.controller('PartnerWidgetController', ['$scope',
    function($scope) {
        $scope.blurb_truncate_length = 180;

        $scope.$watch(function () {
            return $scope.description;
        }, function (result) {
            if (result) $scope.description_text = result;
        });

        $scope.$watch(function(){
           return window.innerWidth * window.innerHeight;
        }, function(value) {
           var the_width = window.innerWidth * 0.55;
           var the_height = window.innerHeight - 100;
           var text_area = Math.floor(the_width * the_height / (12*12) );
           $scope.blurb_truncate_length = text_area;
        });

    }
]);

angular.module('ng').filter('cut', function () {
    return function (value, wordwise, max, tail) {
        if (!value) return '';
        max = parseInt(max, 10);
        if (!max) return value;
        if (value.length <= max) return value;

        value = value.substr(0, max);
        if (wordwise) {
            var lastspace = value.lastIndexOf(' ');
            if (lastspace != -1) {
                value = value.substr(0, lastspace);
            }
        }
        return value + (tail || ' …');
    };
});

1 个答案:

答案 0 :(得分:4)

因为从技术上讲,您正在尝试观看$scope.window,如果您想要侦听窗口大小的变化,请使用:

window.addEventListener('resize', function() {
    $scope.$apply(function(){ 
        $scope.blurb_truncate_length = 2 
    });
}, true);

您还需要使用$scope.$apply来运行摘要周期并使用新值更新范围。

@Terry的更好解释:

  

我在评论中不知道这一点。 $ apply()强制Angular为   执行摘要周期。当一个值是Angular应用程序的一部分时   更改,Angular了解它并更新UI。当一个值   存在于Angular的框架之外(window.something),仅限Angular   当它运行“检查”(循环)时,知道它,$ apply()告诉它做   这张支票。

指向wiki的链接:https://github.com/angular/angular.js/wiki/When-to-use- $ scope。$ apply()