为ng-class应用不同的表达式

时间:2014-06-10 22:01:50

标签: javascript angularjs angularjs-directive angularjs-ng-repeat angularjs-service

您好我试图根据此变量的值更改按钮的颜色:$ 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>

2 个答案:

答案 0 :(得分:1)

我无法测试代码,因为我不知道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的变化情况。确保在角度应用程序内发生更改并开始新的摘要循环。

答案 1 :(得分:1)

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

    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,您不需要{{}},因为它已经使用了表达式或字符串。如果您只是使用它将被评估,您将使用{{}}

 <button class="{{invoice_delete_type_button_styling}}"