有成千上万种方法可以剥这只猫的皮。我知道你特别问的是between{{}},但对于来到这里的其他人,我认为有必要展示一些其他选项。
函数在你的$作用域(在我看来,这是你在大多数情况下最好的选择):
app.controller('MyCtrl', function($scope) {
$scope.foo = 1;
$scope.showSomething = function(input) {
return input == 1 ? 'Foo' : 'Bar';
};
});
<span>{{showSomething(foo)}}</span>
当然是Ng-show和ng-hide:
<span ng-show="foo == 1">Foo</span><span ng-hide="foo == 1">Bar</span>
ngSwitch
<div ng-switch on="foo">
<span ng-switch-when="1">Foo</span>
<span ng-switch-when="2">Bar</span>
<span ng-switch-default>What?</span>
</div>
Bertrand建议的自定义过滤器。(如果你不得不一遍又一遍地做同样的事情,这是你最好的选择)
app.filter('myFilter', function() {
return function(input) {
return input == 1 ? 'Foo' : 'Bar';
}
}
{{foo | myFilter}}
或者一个自定义指令:
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.$watch(attrs.value, function(v) {
elem.text(v == 1 ? 'Foo': 'Bar');
});
}
};
});
<my-directive value="foo"></my-directive>
就我个人而言,在大多数情况下,我会在我的作用域上使用一个函数,它使标记非常干净,而且实现起来又快又容易。除非,也就是说,你要一遍又一遍地做同样的事情,在这种情况下,我会听从Bertrand的建议,根据具体情况创建一个过滤器或指令。
一如既往,最重要的是您的解决方案易于维护,并且希望是可测试的。这完全取决于你的具体情况。