动态添加、链接和呈现指令

Dynamically add, link and render a directive

本文关键字:指令 链接 添加 动态      更新时间:2023-09-26

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

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

是否可以对我在DOM中动态添加的元素动态运行指令?我想把标记弄清楚。

您可以使用$compile服务编译包含指令的模板,并将其附加到页面中。也就是说,如果你不想添加<twitter-stream></twitter-stream>,直到有人点击"添加推特流"按钮,你可以这样做:

<!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>