【问题标题】:applying different expression for ng-class对 ng-class 应用不同的表达式
【发布时间】:2014-07-31 20:11:36
【问题描述】:

您好,我正在尝试根据以下变量的值更改按钮的颜色:$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>

【问题讨论】:

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


    【解决方案1】:

    我认为您只需要在指令中分配类 - 不需要地图对象:

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

    【讨论】:

      【解决方案2】:

      我无法测试代码,因为我不知道如何更改 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 应用程序中并开始一个新的摘要循环。

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多