编辑:请直接进入答案底部以获得最佳版本;答案是按时间顺序排列的;最后,经过几次迭代,我得到了最佳代码。谢谢。
- 我可以覆盖 ng-bind 的行为或默认装饰它吗?
是的。我已经完成了一个非常简单的实现,它使ng-bind 可以按照您的意愿行事。嗯...我不确定这是否正是你想要的,但至少它可以满足我的理解。
工作小提琴:http://jsfiddle.net/93QQM/
这里是代码:
module.directive('ngBind', function() {
return {
compile: function(tElement, tAttrs) {
tAttrs.ngBind = 'myBind(' + tAttrs.ngBind + ')';
return {
pre: function(scope) {
scope.myBind = function(text) {
return angular.element('<div>' + text + '</div>').text();
}
}
};
}
}
});
这并不完全是一个“附加指令”——这是“覆盖 ng-bind 的行为”的方式。它不会添加新指令,它只是扩展现有 ngBind 指令的行为。
在compile 函数中,我们修改ng-bind 属性的值,将其包装到函数调用中。有了这个,我们可以访问原始模型值,并有机会将其修改后返回。
我们在预链接阶段通过作用域使函数可用,因为如果我们在后链接阶段这样做,该函数将仅在在原始 ngBind 指令检索到之后才可用来自属性的值(这将是一个空字符串,因为找不到该函数)。
myBind 函数简单而智能:它创建一个元素,使用文本 - 未更改 - 作为元素主体,只通过 text 函数立即检索 - 将返回内容就像“浏览器呈现”它。
这样,您可以像往常一样使用 ngBind,例如 <div ng-bind="model.content" />,但要修改此行为。
改进版
不是将myBind 函数附加到每个应用了 ngBind 的作用域,而是在每个预链接阶段,我们只能将它附加到$rootScope 一次,使其立即可用于所有作用域。
新的工作小提琴:http://jsfiddle.net/EUqP9/
新代码:
module.directive('ngBind', ['$rootScope', function($rootScope) {
$rootScope.myBind = function(text) {
return angular.element('<div>' + text + '</div>').text();
};
return {
compile: function(tElement, tAttrs) {
tAttrs.ngBind = 'myBind(' + tAttrs.ngBind + ')';
}
};
}]);
比以前的版本干净多了!当然,您可以将myBind 函数名称更改为您想要的任何其他名称。该功能的“成本”是这样的:将这个简单的功能添加到根范围 - 由您决定它是否物有所值。
又一个版本
受 Chemiv 的回答的影响...为什么不从任何范围中删除该功能并使其成为过滤器呢?它也有效。
又一个新的工作小提琴:http://jsfiddle.net/hQJaZ/
还有新代码:
module.filter('decode', function() {
return function(text) {
return angular.element('<div>' + text + '</div>').text();
};
}).directive('ngBind', function() {
return {
compile: function(tElement, tAttrs) {
tAttrs.ngBind += '|decode';
}
};
});
现在您可以从菜单中选择三个选项。