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