【问题标题】:How to make angularJS $watch to detect changes in style?如何让 angularJS $watch 检测风格的变化?
【发布时间】:2015-05-06 21:58:51
【问题描述】:

我有一个包含所有样式控件的富文本框。

当我在其中输入新文本时 - 它会保存。

当我对内容(文本)以及颜色突出显示和粗体文本等样式进行任何更改时,它会保存更改后的文本和样式。

但是,当我只更改样式而不更改任何内容时 - 它不会保存这些样式更改。

我正在使用 $watch 来比较新值和旧值。

如何使它即使在样式更改时也能正常工作?

【问题讨论】:

  • 你能附上你的代码吗?

标签: javascript jquery angularjs scope watch


【解决方案1】:
angular.module("app",[]).directive('spyStyle', [function () {

    return {

        link: function (scope, element, attrs) {

            scope.$watch(function () {
                return element.css(attrs['spyAttribute']);
            },  styleChangedCallBack,
            true);

            function styleChangedCallBack(newValue, oldValue) {
                if (newValue !== oldValue) {
                    // do something interesting here
                }
            }

        }
    };

}]);

在您的 HTML 中:

<div spy-style spy-attribute="height" >

如果你想在指令之外执行自定义函数:

<div spy-style="functionNameToExecute" spy-attribute="height" >

在您的指令代码中进行此更改:

angular.module("app",[]).directive('spyStyle', [function () {

    return {

        link: function (scope, element, attrs) {

            scope.$watch(function () {
                return element.css(attrs['spyAttribute']);
            },  styleChangedCallBack,
            true);

            function styleChangedCallBack(newValue, oldValue) {
                if (newValue !== oldValue) {
                    // do something interesting here
                    // invoking callback function:
                    scope[attrs['spyStyle']](newValue);
                }
            }

        }
    };

}]);

【讨论】:

  • 这种方法不适用于我的情况。我有 Bootstrap 选项卡式表单,我正在观看最后一个具有画布的选项卡的样式属性“显示”。如果“显示”的值从“无”变为“阻止”,那么我想触发调整大小事件来重绘位于该选项卡内的画布。我想我需要调用 $scope.$digest() 才能使其工作,但我不知道如何。我正在使用自定义指令来控制最后一个选项卡并观察显示 css 属性。在调试过程中,我可以看到那个手表,但它似乎运行得太早,并且不能一直正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2017-07-03
  • 2019-03-24
相关资源
最近更新 更多