【问题标题】:Dynamically add, link and render a directive动态添加、链接和渲染指令
【发布时间】:2013-02-22 17:39:26
【问题描述】:

我的标记中有一个标记元素popup-window,我使用相应的指令进行处理。 如果我想在不同的地方显示或隐藏更多这样的小部件,我现在需要将所有这些元素放在我的页面标记中,我不确定这些元素看起来是否干净并且是最好的方法。所以它看起来像这样:

<popup-window></popup-window>
<details-window></details-window>
<share-widget></share-widget>
<twitter-stream></twitter-stream>

是否可以对我在 DOM 中动态添加的元素动态运行指令?我想让标记变得干净。

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    您可以使用 $compile 服务来编译包含指令的模板并将其附加到您的页面。也就是说,如果您不想在有人点击“添加推特流”按钮之前添加&lt;twitter-stream&gt;&lt;/twitter-stream&gt;,您可以执行以下操作:

    <!doctype html>
    <html ng-app="myApp">
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
        <script type="text/javascript">
        var myApp = angular.module('myApp', []);
    
        myApp.controller('MainCtrl', ['$scope', function($scope){
    
        }]);
        myApp.directive('twitterStream', function() {
            return {
                restrict: 'E',
                link: function(scope, elem, attrs) {
                    elem.append('<p>A tweet: ' + Math.random() + '</p>')
                }
            }
        });
        myApp.directive('createTwitterStreamButton', ['$compile', function($compile) {
            return {
                restrict: 'E',
                template: '<button ng-click="add()">Add twitter stream</button>',
                replace: true,
                link: function(scope, elem, attrs) {
                    scope.add = function() {
                        var directiveElement = $compile('<twitter-stream></twitter-stream>')(scope);
                        directiveElement.insertAfter(elem);
                    }
                }
            }
        }]);
        </script>
    </head>
    <body ng-controller="MainCtrl">
        <create-twitter-stream-button></create-twitter-stream-button>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2014-04-02
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多