admin管理员组文章数量:1315312
I have this code and I'm wondering if there is a better style to write this, so that there is less logic in the view.
<span ng-if="status == 'state1' || status == 'state2'">Foobar</span>
<span ng-if="status == 'state3'">Baz</span>
I have this code and I'm wondering if there is a better style to write this, so that there is less logic in the view.
<span ng-if="status == 'state1' || status == 'state2'">Foobar</span>
<span ng-if="status == 'state3'">Baz</span>
Share
Improve this question
asked Apr 7, 2014 at 18:27
crispychickencrispychicken
2,6622 gold badges37 silver badges51 bronze badges
3 Answers
Reset to default 4Yes, I think refactoring is wise. Your example is simple, but it is easy to imagine having many more conditions. I've done something like this, when many elements have plicated display conditions:
$scope.render = {
foobar: function() {
return $scope.status == 'state1' || $scope.status == 'state2'
},
baz: function() {
return $scope.status == 'state3'
}
}
Then the usage in the view is:
<span ng-if="render.foobar()">Foobar</span>
<span ng-if="render.baz()">Baz</span>
Demo: http://plnkr.co/lv4w9dLN8oN0bBF23VKp
This keeps the logic footprint in the view small, and allows you to easily reuse the logic on multiple elements.
Not sure if this is any better, but here is an option using ngSwitch
. It does remove some logic (assuming you only have those three states):
<div ng-switch on="status">
<span ng-switch-when="state3">Baz</span>
<span ng-switch-default>Foobar</span>
</div>
If you expect that your content will grow in future, you can wrap it into directive with template or even so called conditional directive: link
本文标签: javascriptShould I refactor multiple conditions on ngif in angularjsStack Overflow
版权声明:本文标题:javascript - Should I refactor multiple conditions on ng-if in angularjs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741977546a2408211.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论