javascript - 通过将自定义指令分配给 Controller 范围来动态加载自定义指令

标签 javascript angularjs angularjs-directive angularjs-scope

我正在尝试通过单击按钮动态加载我的自定义指令。单击时,我将进行 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/

相关文章:

angularjs - 模板内的嵌套指令放置在顶部

javascript - 如何在 CSS 中为浏览按钮指定样式(图像)?

javascript - 避免在默认值中分配虚假值的陷阱?

javascript - 将 json 数据从 Controller 传递到指令并在 View 中显示

angularjs - 如何扩展 Angular 工厂

javascript - 从 JSON 值中删除括号和引号

javascript - 如何更新单个 firebase firestore 文档

javascript - 使用 Redux 和 React 按顺序执行异步操作

angularjs - 如何使用 AngularJS 的 $resource 和 spring rest Controller 获取 bool 值

javascript - Angular : Bootstrap typeahead with multiselect