所以我有这个代码:
的 HTML:
<span ng-bind-html="generateNavBar(navBar.common, navBar.common[0])"></span>
AngularJS:
var app = angular.module("myApp", ["ngSanitize"]);
app.controller("MainController", ["$scope", function ($scope){
$scope.navBar = {
common: [
["Home", "index.html"],
["Webpage", "index.html"],
["Resources", "index.html"],
["Login", "index.html"],
["Who we are", "index.html"]
]
}
$scope.generateNavBar = function (items, current){
var navigator = '<nav><ul><b>';
for (i = 0; i < items.length; i++)
{
if (items[i] == current)
{
navigator += '<a href="' + items[i][1] + '"><li id="current">' + items[i][0] + '</li></a>';
}
else
{
navigator += '<a href="' + items[i][1] + '"><li>' + items[i][0] + '</li></a>';
}
}
navigator += '</b></ul></nav>';
return navigator;
}
}]);
函数generateNavBar(items, current)
用于生成每个页面的导航栏。该函数通过生成html然后将其返回来工作。它运行正常,但问题是它显然无法通过html传递id="current"
所以我尝试传入style="border-bottom: 1px solid #000"
但这也无效。我知道这不是代码的问题,因为当我console.log(navigator)
它返回带有id的HTML时。我做错了什么或只是AngularJS的限制?如果是这样,我可以使用不同的方法吗?
答案 0 :(得分:1)
正如Alon Eitan所指出的,你可能错过了使用angular js指令的正确方法,但是对于你的代码,你必须首先在返回字符串时添加trustAshtml
var app = angular.module("myApp", ["ngSanitize"]);
app.controller("MainController", ["$scope","$sce", function ($scope,$sce){
$scope.navBar = {
common: [
["Home", "index.html"],
["Webpage", "index.html"],
["Resources", "index.html"],
["Login", "index.html"],
["Who we are", "index.html"]
]
}
$scope.generateNavBar = function (items, current){
var navigator = '<nav><ul><b>';
for (i = 0; i < items.length; i++)
{
if (items[i] == current)
{
navigator += '<a href="' + items[i][1] + '"><li id="current">' + items[i][0] + '</li></a>';
}
else
{
navigator += '<a href="' + items[i][1] + '"><li>' + items[i][0] + '</li></a>';
}
}
navigator += '</b></ul></nav>';
return $sce.trustAsHtml(navigator);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.2.29/angular-sanitize.min.js"></script>
<div ng-app="myApp" ng-controller="MainController">
<span ng-bind-html="generateNavBar(navBar.common, navBar.common[0])"></span>
要记住的另一件事是确保您的角度js版本和角度消毒版本是相同的。