Javascript AngularJS异步指令编译

Javascript AngularJS异步指令编译,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我正在编写一个angularjs应用程序(带有node/express后端)。我的作用域中有一个对象,它通过服务异步填充(和重新填充) 对象的内容是一系列“问题”对象,为了简单起见,这些对象具有“文本”和“类型”属性 我试图实现的是,每种类型都能有一个角度指令,并且能够正确地渲染这些指令。例如,如果服务器返回[{type:'booleanquestion',text:'Is the sky blue?}],我将创建一个元素,然后booleanquestion指令将启动并适当地呈现它 到目前为止,

我正在编写一个angularjs应用程序(带有node/express后端)。我的作用域中有一个对象,它通过服务异步填充(和重新填充)

对象的内容是一系列“问题”对象,为了简单起见,这些对象具有“文本”和“类型”属性

我试图实现的是,每种类型都能有一个角度指令,并且能够正确地渲染这些指令。例如,如果服务器返回[{type:'booleanquestion',text:'Is the sky blue?}],我将创建一个元素,然后booleanquestion指令将启动并适当地呈现它

到目前为止,我已经定义了一个“questionset”指令,该指令运行良好,可以查看问题集合并编译所需的内容,从而使指令显示正确

Html 指令.js
angular.module('myApp')。指令('questionset',函数($compile){
返回{
排除:'正确',
编译:函数(元素、属性、链接器){
返回函数($scope、$element、$attr){
var元素=[],
parent=$element.parent();
$scope.$watchCollection('questions',函数(questions){
var块,i,childScope;
如果(elements.length>0)
{
对于(i=0;i
虽然这是工作正常,我有两个问题

1) 。这是一种“正确”的方法吗?这是我的第一个角度项目,似乎我已经跳到了相当深的一端(或者这就是它的感觉)

2) 。我的下一个目标是让question.text能够包含HTML,并对其进行“编译”。例如,文本可能是

"Is the <strong>sky</strong> blue?"
“天空是蓝色的吗?”
我不知道该如何实现这一点——正如我在代码中的注释所示,出于某种原因,$compile没有被注入到我的布尔指令中。也许这是因为我手动为它创建了子范围?我试图再次编译元素的内容,对吗?我觉得最后一点可能很简单,但我没有看到。

1)我不知道。在我看来,整体方法似乎很好;只需要擦亮它,我们将在下面看到

2) 可能$compile在嵌套函数中不可用,因为它未在父级中使用。尝试在父函数中引用$compile,看看这是否真的是原因:

angular.module('achiive-vision').directive('boolean',function($compile){
    var justTesting = $compile;
    return {
        restrict: 'AC',
        template: '<div class="question">{{question.text}}</div>',
        replace: true,
        link: function(scope,elem,attrs,ctrl){
            …….
       // check if $compile is defined here now
        }
    };
});
这样,您就不需要再次编译,而且您已经获得了HTML支持

还有,这有点奇怪

var html = '<div class="'+questions[i].type+'"/>';
(另外,我会避免将变量命名为“I”和“e”。)

以下是我对您的代码的评论。正如我所说的,我认为这种方法非常好,对于刚开始学习AngularJS的人来说,更不用说“高级”。我自己只用了不到两个月的时间

"Is the <strong>sky</strong> blue?"
angular.module('achiive-vision').directive('boolean',function($compile){
    var justTesting = $compile;
    return {
        restrict: 'AC',
        template: '<div class="question">{{question.text}}</div>',
        replace: true,
        link: function(scope,elem,attrs,ctrl){
            …….
       // check if $compile is defined here now
        }
    };
});
var html = '<div class="question ' + questions[i].type + '">'
           + questions[i].text + '</div>';
var html = '<div class="'+questions[i].type+'"/>';
template: '<div class="question">{{question.text}}</div>',
var block, i, childScope, html, e;