我应该在哪里把ngClass逻辑,如果不是在控制器? [英] Where should I put ngClass logic if not in the controller?

查看:124
本文介绍了我应该在哪里把ngClass逻辑,如果不是在控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个价值 - >类这是我们用来属性的值映射到一个给定的CSS类查找。

我不希望这样的逻辑内联,所以目前它在控制器,它保持code非常简单。然而,这违反了没有在控制器UI逻辑的原则。所以,还有什么地方我可以把这个同时保持code干净吗?

这是我目前有:

控制器:

  app.controller('myController的',函数($范围){    VAR statusClassMap = {
        PausePending':'标签标签默认,
        '暂停':'标签,标签的主',
        ContinuePending':'标签,标签信息,
        StartPending':'标签,标签信息,
        '运行':'标签,标签成功',
        StopPending':'标签,标签警告,
        '停止':'标签,标签危险
    };    $ scope.statusClassMap = statusClassMap;
});

查看:

 < TD><跨度数据-NG-CLASS =statusClassMap [service.Status]> {{service.Status}}< / SPAN>< / TD>


解决方案

其完美的罚款在我看来,有在控制器(冗长和复杂的)查看相关的东西,以保持视图杂波免费的。

我会在特别地专用于此目的的范围的模型属性。这保持一切逻辑分组:

  $ scope.myModel = {
    观点:{
        //所有视图相关的东西放在这里
    },
    ...
}

使用 NG-INIT 如果你仍然preFER保持它的视图中:

 < D​​IV NG-的init =statusClassMap = {...};>

I have a value -> class lookup that's used to map values of a property to a given CSS class.

I don't want this logic inline, so at the moment it's in the controller, which keeps the code very simple. However this violates the principle of not having UI logic in controllers. So where else could I put this whilst keeping the code clean?

This is what I currently have:

Controller:

app.controller('MyController', function ($scope) {

    var statusClassMap = {
        'PausePending': 'label label-default',
        'Paused': 'label label-primary',
        'ContinuePending': 'label label-info',
        'StartPending': 'label label-info',
        'Running': 'label label-success',
        'StopPending': 'label label-warning',
        'Stopped': 'label label-danger'
    };

    $scope.statusClassMap = statusClassMap;
});

View:

<td><span data-ng-class="statusClassMap[service.Status]">{{service.Status}}</span></td>

解决方案

Its perfectly fine in my opinion to have (lengthy and complex)view-related stuff in the controller to keep the view clutter-free.

I would have a model property in the scope that is specifically dedicated for this purpose. This keep everything logically grouped:

$scope.myModel = {
    view: {
        // all view-related stuff goes here
    },
    ...
}

Use ng-init if you still prefer keeping it inside the view:

<div ng-init="statusClassMap = {...};">

这篇关于我应该在哪里把ngClass逻辑,如果不是在控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆