【问题标题】:ng-style Variable Not Updating When Scope is Updated更新范围时不更新 ng-style 变量
【发布时间】:2015-10-16 02:49:25
【问题描述】:

我正在监视一个 CSS 样式并更新基于该 CSS 样式值的范围内的变量。它第一次工作,但是当浏览器调整大小时,范围会更新,但 ng-style 不会使用新的范围参数更新。

JS:

.directive('monitorStyle', function() {
        return {
            link: function(scope, element, attrs) {
                scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle);
                angular.element(window).on('resize', function() {
                    scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle);
                });

            }
        }
    })

HTML:

<p class="text" monitor-style="font-size" update-variable="textHeight">Press "<img class="mini up" src="img/select-arrow.png" src="Up" ng-style="{'height': textHeight}">

我正在尝试在控制器之外执行此操作,因为这是人们推荐的。为什么更新范围时ng-style不更新?

【问题讨论】:

标签: angularjs


【解决方案1】:

窗口事件不是角度事件,所以角度不知道他必须更新模型/范围。您必须添加 scope.$apply() 来告诉 Angular 刷新它:

angular.element(window).on('resize', function() {
    scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle);
    scope.$apply();
});

数据绑定仅在您的模型使用 $http、$timeout、ng-click 等角度事件更新时才有效...

一篇很棒的文章:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

【讨论】:

  • 注意:我正在尝试这个但应用了 scope.$apply();在 angular.element(window) 调整大小之外,它给了我 $digest in progress 错误,因为你调用了 scope.$apply too early
【解决方案2】:

哟,我做了这个病态的解决方案。

因此,如果您想查看样式(甚至是特定元素上的一组样式),然后将它们的值发送到 $scope,您可以使用这个 JS:

.directive('monitorStyle', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            function addToScope() {
                var updateVariable = attrs.updateVariable.split(',');
                var monitorStyle = attrs.monitorStyle.split(',');
                for (var i = 0; i < updateVariable.length; i++) {
                    scope[updateVariable[i]] = $(element).css(monitorStyle[i]);
                }
            }
            addToScope();
            angular.element(window).on('resize', function() {
                addToScope();
                scope.$apply();
            });
        }
    }
})

并像这样应用它:

<h2 monitor-style="font-size,line-height" update-variable="headerHeight,headerLineHeight">

这将在初始化和调整窗口大小时更新 $scope。您当然可以根据自己的目的对其进行修改。

每次 $scope 更改时,您都可以像这样更新其他样式:

<div ng-style="{'height': headerHeight, 'line-height': headerLineHeight}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多