我正在尝试通过单击按钮动态加载我的自定义指令。单击时,我将进行 AJAX 调用来获取指令 html。一旦我得到响应,我就会编译该响应并将其分配给 Controller 范围变量。我期望自定义指令的相应模板能够正确显示,但事实并非如此。请帮忙。
下面是具有相同问题的代码示例。
在我的 HTML 文件中:
<body ng-app="sampleApp" ng-controller="DemoController as DemoCtrl">
<div ng-bind-html="test">
<md-button class="md-raised md-primary" ng-click="DemoCtrl.getDirective()">Click to get directive</md-button>
</body>
我的模块和相应的 Controller /指令:
angular.module('sampleApp',['ngMaterial'])
.directive('test',function(){
return {
restrict: 'E',
template: '<B>Hello World</B>'
};
})
.controller('DemoController', function($compile,$scope,$sce) {
var vm = this;
vm.getDirective = function(){
//Here I make a service call to get the directive. In this case I get a response as <test></test>
var directiveCode = $compile("<test></test>");
var directiveHTML = directiveCode($scope);
$scope.test = $sce.trustAsHtml(directiveHTML);
$scope.$apply();
}
});
最佳答案
试试这个
angular.module('sampleApp',['ngMaterial'])
.directive('test',function(){
return {
restrict: 'E',
template: '<B>Hello World</B>'
};
})
.controller('DemoController', function($compile,$scope,$sce) {
var vm = this;
vm.getDirective = function(){
//Here I make a service call to get the directive. In this case I get a response as <test></test>
var directiveCode = $compile("<test></test>");
var directiveHTML = directiveCode($scope);
console.log(directiveHTML.html());
$scope.test = $sce.trustAsHtml(directiveHTML.html());
//$scope.$apply();
}
});
关于javascript - 通过将自定义指令分配给 Controller 范围来动态加载自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37037635/