我有一个填充了ng-repeat的列表。然后,我有一个基于内容类型字段设置内容格式的指令。我想在注入的 HTML 上添加指令。这怎么可能?下面是我的代码。if 语句中的第二条语句不起作用(使用 ng-bind)。
angular.module('mobileDashboardApp')
.directive('detailFormat', function () {
return {
link: function postLink(scope, element, attrs) {
var entry = scope.entry;
if(entry.type === 'action') {
element.append('<button>' + entry.value + '</button>');
} else if (entry.type === 'event') {
element.append('<button ng-bind="entry.value"></button>');
} else if(entry.type === 'comment') {
element.append('<strong>Note:</strong> ' + entry.value);
}
}
};
});
为什么你不使用HTML中的标记?一般来说,在使用 Angular 和 Ember 等框架时,自己操作 DOM 是一个糟糕的主意,因为它们可能会践踏你的所有更改,并对渲染的内容感到困惑。
您可以使用一些强大的模板构造来执行此操作,例如 ng-if。
<div ng-if="entry.type === 'action'">put something here<div>
<div ng-if="entry.type === 'event'">put something here<div>
<div ng-if="entry.type === 'comment'">put something here<div>
希望这是有帮助的。