对ng类应用不同的表达式

applying different expression for ng-class

本文关键字:表达式 应用 ng      更新时间:2023-09-26

嗨,我试图改变一个按钮的颜色基于这个变量的值:$scope.order.orderwindow.invoicedata。

我改变了ng-class中的表达式来做到这一点。然而,现在它没有改变,尽管我的手表功能。

directive.js

 .directive('invoicetypewatch', function() {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
    // change styling of button depending on if id is null or not
    scope.$watch('order.orderwindow.invoicedata', function() {
      if(scope.order.orderwindow.invoicedata.id!=null) {       
    scope.invoice_delete_type_button_styling={"btn btn-danger btn-block":true};
        }else{
        scope.invoice_delete_type_button_styling={"btn btn-danger btn-block":false};
        }
      });
    }
    };
    })

view.html

 <div class="col-lg-4" invoicetypewatch>
<button ng-class="{{invoice_delete_type_button_styling}}" ng-click="delete(invoice_delete_type_button,order.orderwindow.invoicedata.id)">{{invoice_delete_type_button}}</button>
</div>

我认为你只需要在指令中分配类-不需要映射对象:

    if(scope.order.orderwindow.invoicedata.id!=null) {       
       scope.invoice_delete_type_button_styling="btn btn-danger btn-block";
    }else{
         scope.invoice_delete_type_button_styling="btn btn-success";
    }

然后在ng-class中使用该作用域变量而不使用{{}},因为ng-class会计算

中传递的任何内容。
  <button ng-class="invoice_delete_type_button_styling"

对于ng-class不需要{{}},因为它已经接受一个表达式或字符串。如果你只使用class,你会使用{{}},它会被求值

 <button class="{{invoice_delete_type_button_styling}}"

我无法测试代码,因为我不知道order.orderwindow.invoicedata是如何改变的,但我的建议是完全放弃watch并将视图更改为:

<div class="col-lg-4" invoicetypewatch>
<button ng-class="{'btn btn-danger btn-block':(scope.order.orderwindow.invoicedata.id!=null)}"
  ng-click="delete(invoice_delete_type_button,order.orderwindow.invoicedata.id)"> {{invoice_delete_type_button}}</button>
</div>

这可以工作,但它仍然取决于order.orderwindow.invoicedata如何变化。确保这个修改发生在你的angular应用中,并开始一个新的摘要循环。