通过将自定义指令分配给控制器作用域来动态加载它

时间:2016-05-04 20:42:37

标签: javascript angularjs angularjs-directive angularjs-scope

我试图在点击按钮时动态加载我的自定义指令。点击后,我会进行AJAX调用以获取指令html。一旦我得到响应,我编译该响应并将其分配给控制器范围变量。我希望自定义指令的相应模板能够正确显示,但事实并非如此。请帮忙。

以下是具有相同问题的代码示例。

在我的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>

我的模块和相应的控制器/指令:

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();
            }
        });

2 个答案:

答案 0 :(得分:0)

试试这个

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();
            }
        });

答案 1 :(得分:0)

感谢您的帮助@Awolf和@wasiq。您的代码段工作正常。

在我的情况下问题是我甚至在AJAX调用解决之前就将指令的模板分配给控制器范围。因此,我没有在DOM中获得指令的模板。现在我将范围变量赋值移到了成功块中,这解决了这个问题。