我的问题如下:
$compile
允许您在指令中解释角度,运行$compile
时,也不会创建DOM元素。因此,在HTML中键入的任何指令都不适用于$compile
。因为一个简单的例子是最好的:
var testApp = angular.module('testApp',[]);
testApp.controller('loadCtrl', ['$scope', '$compile', function($scope, $compile){
var divElement = angular.element(document.querySelector("#include"));
var appendHtml = $compile('<test></test>')($scope);
divElement.append(appendHtml);
}]);
testApp.directive('test', function(){
return{
restrict: 'E',
template: '<div id="test" ng-controller="testCtrl">Test Div</br>'+
'{{angularloads}}</div>'
};
});
testApp.controller('testCtrl', ['$scope', function($scope){
test = function(){
angular.element(document.querySelector('#test')).append('<div id="never">Success !</div>');
return "$compile works... and yet, you will never see the 'Success !' ...";
};
$scope.angularloads = test();//defines by test to show that test() does run !
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div id="mybody" ng-app="testApp">
Using append :
<div id="include" ng-controller="loadCtrl">
</div>
</div>
如果您尝试使用代码段在HTML代码中输入<test></test>
,那么您可以查看最棒的内容!
提前感谢您的建议!