javascript - 对 ng-class 应用不同的表达式

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

您好,我正在尝试根据此变量的值更改按钮的颜色:$scope.order.orderwindow.invoicedata。

我正在更改 ng-class 中的表达式来执行此操作。然而,尽管我有 watch 功能,但现在它并没有改变。

指令.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};
        }
      });

    }
    };
    })

查看.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>

最佳答案

我认为你只需要在指令中分配类 - 不需要 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}}"

关于javascript - 对 ng-class 应用不同的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24151586/

相关文章:

javascript - this.setState 无法正常工作

javascript - 尝试输出对象的属性时出错

javascript - 如何使用 ng-grid 在单元格模板上应用字段

javascript - Angular : View doesn't update when a value in $scope changes

javascript - 无法修复我的 angularjs 应用程序路径中的主题标签

javascript - 在 ng-view 中禁用弹性滚动,但不在 ng-include 的 subview 中禁用弹性滚动

javascript - Angular 可排序遏制防止掉落操作

javascript - Bing map 获取以预定义距离间隔落在该路线上的位置的路线路径坐标

javascript - AngularJS 在循环内动态创建指令

javascript - 我可以观察指令中属性的变化吗?