AngularJS - 使用纯JavaScript或服务计算CSS类



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

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。

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

你不需要一个函数来根据作用域值设置类,使用接受一些javascript条件的ng-class

<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,
    }
}

演示

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

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

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>

最新更新