假设我们正在从服务器获取一些数据。
data = {
"value": "123456",
"included": true,
"invalid": true,
"warning": false,
"error": false,
}
根据布尔状态,值需要以特定样式显示。我目前正在做的是将数据格式化为 JS 构造函数
$scope.model = new SomePrototype(data);
推断您计算规则的 CSS(在伪代码中):
var SomePrototype = function (data) {
this.computeCSS = function () {
if data.error then css = 'danger'
if (data.included and data.invalid) then css = 'danger'
/*other rules*/
return css
}
}
然后在 HTML 视图中调用 computeCSS()
<p class="{{model.computeCSS()}}">{{model.value}}</p>
呈现为
`<p class="danger">123456</p>`
问题:首先,我在其他地方没见过这样的东西。所以我可能会做错事。通常你会在 $scope 下获得一个对象来保存类值。其次,它需要在每个控制器中调用 SomePrototype。
我想知道使用服务/工厂是否更合法。最终结果对我来说看起来基本相同。