我注意到当 DOM 上的某些元素需要 Angular 的各种条件类时,HTML 页面变得多么困惑和不可读。
像这样:
<div>This is a Message.</div>
很容易变成这样:
<div ng-class="{'red': vm.isRed, 'bold': vm.isBold, 'big': vm.isBig, 'underline': vm.isUnderline}">This is a Message.</div>
或者更大的东西。我想问的是是否有任何常见的做法可以从 HTML 中排除这种逻辑?
也许是这样的:
<div ng-class="objectClass">This is a Message.</div>
并将其放在 Controller 上:
vm.isRed = true;
vm.isBold = true;
vm.isBig = true;
vm.isUnderline = false;
vm.objectClass = {
'red': vm.isRed,
'bold': vm.isBold,
'big': vm.isBig,
'underline': vm.isUnderline,
};
最佳答案
我通常使用您在 objectClass
示例中使用的符号或 array notation :
<something ng-class="[source]">
和
$scope.source = ['red', 'bold', 'big'];
关于 eBay blog他们定义了好的模板的标准:
- 不包括业务逻辑
- 不包含太多逻辑
- 易于阅读
- 易于维护
虽然避免第一点很容易,ng-class
使在模板中创建逻辑表达式变得如此容易,它引诱您进入其他危险(即:只需添加另一个表达式在某些时候你很难理解模板表达式)。
我认为 eBay 博客的作者一语中的:
Although I’m trying to make a case against logic-less templates, that does not mean that I am advocating the other extreme–i.e., a templating language that allows a lot of logic. I find such templating languages, especially those that allow the host programming languages to be used inside the template, to be hard to read, hard to maintain, and simply a bad choice. A JSP template with Java code in it and an Underscore template with JavaScript in it both fall into the category of being a full-of-logic template. JSP and Underscore are not necessarily at fault here; rather, developers often abuse the additional freedom such solutions offer.
因此,虽然我喜欢 ng-class
给我的自由,但我试图限制自己并将逻辑插入 Controller 。
关于javascript - 从 DOM 中排除 ng 类逻辑是常见的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021797/