指令中重新渲染模板

指令中重新渲染模板

本文介绍了如何在 AngularJS 指令中重新渲染模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个生成 Twitter 按钮的指令.由于这些按钮上的范围变量可能会改变,我需要在它发生时重建按钮.目前,我正在使用 jQuery empty() 链接元素并重建按钮.

I've create a directive that generates Twitter buttons. Since the scope variables on those buttons may change, I need to rebuild the button when it happens. Currently, I'm using jQuery to empty() the linked element and rebuild the button.

app.directive 'twitterShare', ($timeout, $window) ->
    restrict: 'E'
    template: '<a href="https://twitter.com/share" class="twitter-share-button" data-text="{{ text }}" data-url="{{ url }}">Twitter</a>'
    scope:
        text: '@'
        url: '@'
    link: (scope, el, attrs) ->
        scope.$watch 'text', -> rebuild()
        scope.$watch 'url' , -> rebuild()

        rebuild = ->
            $(".twitter-share-button").remove()
            tweet = $ '<a>'
            .attr 'href', 'https://twitter.com/share'
            .attr 'id', 'tweet'
            .attr 'class', 'twitter-share-button'
            .attr 'data-lang', 'en'
            .attr 'data-count', 'none'
            .text 'Tweet'

            el.prepend tweet
            tweet.attr 'data-text', scope.text
            tweet.attr 'data-url', scope.url
            $window.twttr.widgets.load()

有没有办法让指令完全重新渲染模板?

Is there any way to get the directive to completely re-render the template instead?

推荐答案

这是一个可重用的指令,您可以使用它在发送事件时重建嵌入的内容:

Here is a reusable directive you could use that will rebuild the transcluded content whenever an event is sent:

app.directive('relinkEvent', function($rootScope) {
    return {
        transclude: 'element',
        restrict: 'A',
        link: function(scope, element, attr, ctrl, transclude) {
            var previousContent = null;

            var triggerRelink = function() {
                if (previousContent) {
                    previousContent.remove();
                    previousContent = null;
                }

                transclude(function (clone) {
                    element.parent().append(clone);
                    previousContent = clone;
                });

            };

            triggerRelink();
            $rootScope.$on(attr.relinkEvent, triggerRelink);

        }
    };

});

这是一个 jsFiddle 演示它是如何工作的:http://jsfiddle.net/robianmcd/ZQeU5/

Here is a jsFiddle demoing how it works: http://jsfiddle.net/robianmcd/ZQeU5/

请注意每次单击触发重新链接"按钮时输入框的内容如何重置.这是因为每当触发事件时,输入框都会被移除并添加到 DOM 中.

Notice how the content of the input box gets reset every time you click the "Trigger Relink" button. This is because the input box is being remove and added to the DOM whenever the event is triggered.

您可以按原样使用此指令或对其进行修改,使其由 scope.$watch() 而不是事件触发.

You could use this directive as is or modify it so that it is triggered by scope.$watch() instead of an event.

这篇关于如何在 AngularJS 指令中重新渲染模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!