javascript - 如何将 HTML 从 Controller append 到指令模板 AngularJS - 错误无法插值

标签 javascript angularjs compilation append interpolation

我的 AngularJS Controller 中有一个函数:

//some stuff from controller

var variable1;
var variable2; 

$scope.setTitle = function () { 
            if ( //sth) {
                variable1 = "string"
                return variable1;
            }
            else {
                (function () {
                    //setting the variable2 - it will be the HTML code
                      variable2 = angular.element(document.querySelector('titleID'));
                      variable2.append(title);                        
                })();
            return variable2;
            }
        };

我从 JSON 文件获取 title,它看起来像:

 title = "Return product: <span data-ng-bind=\"productRet.ID\" />"

我必须使用JSON文件,因为我在这个JSON文件中有一个大“树”,并且标题根据函数内部发生的情况而不同 > 在 else 语句中

我在指令模板中调用 setTitle():

.directive('myDirective', ['$compile', function ($compile) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var template = { 
                             <!-- a lot of HTML -->
                             + "<div id=\"titleID\">"
                                 + "<span class=\"navbar-brand\" > {{setTitle()}} </span>"
                             + </div>
                           };

            templateObj = $compile(template)(scope);
            element.append(templateObj);
            }
        }
     }]);

如果 setTitle() 的结果是 variable1 一切都很好。问题是当结果为 variable2 时,因为我收到错误:

"[$interpolate:interr] Can't interpolate: {{setTitle()}}
Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed! Expression: setTitle()

如何将variable2中的HTML代码正确插入到我的模板中?

最佳答案

(function () {
                    //setting the variable2 - it will be the HTML code
                      var variable2 = angular.element(document.querySelector('titleID'));
                      variable2.append(title);                        
                })();
            return variable2;

variable2 在函数作用域之外不可用。 尝试这样的事情:

var variable2;
(function () {
    //setting the variable2 - it will be the HTML code
    variable2 = angular.element(document.querySelector('titleID'));
    variable2.append(title);                        
})();
return variable2;

关于javascript - 如何将 HTML 从 Controller append 到指令模板 AngularJS - 错误无法插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31583201/

相关文章:

angular - Angular 2 Ahead-of-Time 编译器是否支持 SASS 样式表?

c# - 使用 C++ 调试器作为反射替代

compilation - OCR Computer Science GCSE 关于编译器和解释器的错误?

javascript - 从 HTML 元素获取 DataTable 对象

javascript - 更改数据和时间格式

Javascript:根据几个键值对(但不是全部)从对象数组中仅获取重复值

javascript - Angularjs 1x 将函数传递给 AngularJS 指令

javascript - 如何从angularjs中的选择框获取选定的值

javascript - Angularjs动态循环访问数组键的动态值

javascript - 从 Repeater QML/JS 创建一个动态数量的 AppCheckBoxes