1

假设我们正在从服务器获取一些数据。

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。

我想知道使用服务/工厂是否更合法。最终结果对我来说看起来基本相同。

4

2 回答 2

3

您不需要一个函数来根据范围值设置类,使用ng-class它接受一些 javascript 条件

<p ng-class="{danger: data.error || data.included && data.invalid} ">{{data.value}}</p>

function Ctrl($scope) {
    $scope.data = {
        "value": "123456",
            "included": true,
            "invalid": true,
            "warning": false,
            "error": false,
    }
}

DEMO

于 2013-11-06T12:38:12.877 回答
2

您走在正确的轨道上,但是我会ng-class按照 charlietfl 的建议使用。

将逻辑保留在您提到的函数内部,您可以对被认为是模型无效状态的规则进行单元测试。(您的条件很简单,但在您的视图中有逻辑通常并不理想)

模型

var SomePrototype = function (data) {

    this.isDataInValid = function () {
        return data.error || data.included && data.invalid;
    }
}

测试

it('should be invalid with error or included && invalid', function () {

    var data = {
        "value": "123456",
        "included": true,
        "invalid": true,
        "warning": false,
        "error": false,
    }
    var someModel = new SomePrototype(data);
    var isDataInValid = someModel.isDataInValid();
    expect(isDataInValid).toBe(true);
});

在你的<html/>

<p ng-class="{danger : model.isDataInValid() } ">{{model.value}}</p>
于 2013-11-06T12:41:28.900 回答