javascript AngularJS:在指令中观察 element.html()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16590765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:14:25  来源:igfitidea点击:

AngularJS : Watch element.html() in a directive

javascriptangularjsmarkdownangularjs-directive

提问by PonteIneptique

I am looking to create a mardown directive(restrict A) which would make me able to use same recipient for ng-view. So I would basically load only .md files in views and apply my function on its content each time ng-view change. So :

我希望创建一个mardown 指令(限制 A),这将使我能够对ng-view使用相同的收件人。所以我基本上只会在视图中加载 .md 文件,并在每次 ng-view 更改时对其内容应用我的函数。所以 :

index.html

索引.html

<div markdown ng-view></div>

with two views containing, let say, view1.md

有两个视图包含,比如说,view1.md

#That should be h1

and view2.md

view2.md

##That should be h2, no ?

My actual code is

我的实际代码是

'use strict';
angular.module('btford.markdown', []).
  directive('markdown', function () {
    var converter = new Showdown.converter();

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            scope.$watch(element.html(), function(value) {
                    var htmlText = converter.makeHtml(element.html());
                    element.html(htmlText);
            });

            var htmlText = converter.makeHtml(element.text());
            element.html(htmlText);
        }
    }
});

回答by Vince

The first param of watch can be a function, return any value you want including your $element.html(). You can even do a combination of data

watch 的第一个参数可以是一个函数,返回任何你想要的值,包括你的 $element.html()。你甚至可以做数据的组合

$scope.$watch(
    function() { return $element.attr("abc") + $scope.variable + someinternalvar; },
    function(newVal, oldVal) { doTheStuff(); }
);

Obviously the more intense the data you put in here the slower your watches will be. Use caution.

显然,您输入的数据越密集,您的手表就越慢。谨慎使用。

-- FYI

- 供参考

You should clean up your watchers, create an array and push the results of $scope.$watch into that array. Then on the $destroy message remove them. Also remember to unbind events as they will cause eventual performance issues as scopes are created & destroyed.

您应该清理您的观察者,创建一个数组并将 $scope.$watch 的结果推送到该数组中。然后在 $destroy 消息中删除它们。还要记住取消绑定事件,因为它们会在创建和销毁作用域时导致最终的性能问题。

$document.bind('click', clickMe);
$(window).on("resize", winResize);

var watches = []

watches.push($scope.$watch("thing", function() { Thing(); }));

$scope.$on("$destroy", function () {
    for (var i in watches) watches[i]();
    $document.unbind('click', clickMe);
    $(window).off("resize", winResize);
});

-- EDIT 2016-07-14

-- 编辑 2016-07-14

Just to add, cleaning up scope watchers is not needed as they are already processed internally, however rootScope, parent, etc. you should absolutely cleanup.

补充一点,不需要清理范围观察者,因为它们已经在内部处理,但是 rootScope、父级等,你应该绝对清理。

回答by f1lt3r

It may be cleaner for you to use the $stateChangeSuccessevent inside your directive rather than setting your own $watch. Try adding a callback function to the $stateChangeSuccessevent, this should trickle down to the scope of your directive.

$stateChangeSuccess在指令中使用事件而不是设置自己的 $watch对您来说可能更干净。尝试向$stateChangeSuccess事件添加回调函数,这应该会渗透到您的指令范围内。

'use strict';

angular.module('btford.markdown', []).
  directive('markdown', function () {
    var converter = new Showdown.converter();

    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            // When the state is change to, or reloaded...
            scope.$on('$stateChangeSuccess', function () {
                var htmlText = converter.makeHtml(element.text());
                element.html(htmlText);
            });
        }
    }
});

回答by TheHippo

You can only watch variables on your scope.

您只能在您的范围内观察变量。

scope.foo = 'bar';
scope.$watch('foo', function(newValue) {
  // Code to execute here
});

If you want to monitor the changes of DOM elements you need to do this on your own.

如果你想监控 DOM 元素的变化,你需要自己做。