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/

相关文章:

javascript - 指令在引导网格中工作很奇怪

AngularJS - 同时检测未定义的空值或空值的最佳方法是什么?

javascript - Polymer 的动画页面与 Angularjs 一起使用

使用多个编译器编译 C 代码

c++ - 使用 MSYS2 编译 C++ Windows exe 独立文件

javascript - jQuery datepicker 上一个和下一个按钮不显示,如何在 css 中指向主题文件夹图像

javascript - 如何执行将 JS 函数作为字符串传入而不使用 eval 的函数调用?

javascript - 获取\p{L}+来匹配字符串

c++ - 使用 GCC 编译 .CPP

javascript - 分组然后过滤