【发布时间】:2016-01-11 22:18:37
【问题描述】:
首先,我的做法可能不正确。但我会解释这个问题:
1) 我正在创建名为
2) 当点击第一个指令中的按钮时,我试图在运行时动态插入第二个指令
如下:
<!DOCTYPE html>
<html>
<script src="lib/angular/angular.js"></script>
<body ng-app="myApp">
<first-directive></first-directive>
<script>
var app = angular.module("myApp", []);
app.directive("firstDirective", function() {
return {
template : '<h1>This is first directive!</h1> <br / ><br / ><button type="button" ng-click="firstCtrl()">Click Me to second directive!</button> <div id="insertSecond"></div> ',
controller: function ($scope) {
$scope.firstCtrl = function($scope) {
angular.element(document.querySelector('#insertSecond')).append('<second-directive></second-directive>');
}
}
}
});
app.directive("secondDirective", function() {
return {
template : '<h1>This is second directive!</h1> <br / ><br / >',
controller: function ($scope) {
}
}
});
</body>
</html>
但它不起作用,我的意思是,它正在插入“ second-directive >”文本,而不是上面指令中的内容。
我是 Angular js 的新手,我认为我们可以用不同的方式来做到这一点,或者我的方法本身是不正确的。但我只想动态插入第二个指令。
编辑::感谢 George Lee,我得到了解决方案:
解决方案是我们必须编译如下,但没有将作用域对象传递给函数:
<!DOCTYPE html>
<html>
<script src="lib/angular/angular.js"></script>
<body ng-app="myApp">
<first-directive></first-directive>
<script>
var app = angular.module("myApp", []);
app.directive("firstDirective", function($compile) {
return {
templateUrl : '<h1>This is first directive!</h1> <br / ><br / ><button type="button" ng-click="firstCtrl()">Click Me to second directive!</button> <div id="insertSecond"></div> ',
controller: function ($scope) {
$scope.firstCtrl = function() {
var ele = $compile('<second-directive></second-directive>')($scope);
angular.element(document.querySelector('#insertSecond')).append(ele);
}
}
}
});
app.directive("firstDirective", function() {
return {
templateUrl : '<h1>This is second directive!</h1> <br / ><br / >',
controller: function ($scope) {
}
}
});
另外,这个link 很好地解释了如何动态编译和注入模板。
【问题讨论】:
标签: javascript angularjs angularjs-directive