您可以使用 $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>