首页 > 解决方案 > 无法让 AngularJS 应用程序中的 CSS 立即更新

问题描述

我希望有一些 Angular 1.x 专家可以告诉我我做错了什么。我有一个简单的功能来更新“标签组”中的 3 个按钮中的哪一个是当前按钮。每当单击任何按钮时都会调用此函数。

        $scope.updateFilter = function (type, value) {
            // Additional unrelated code here ...

           document.getElementsByClassName('active')[0].className = document.getElementsByClassName('active')[0].className.replace(' active', '');
           document.getElementById('tabButton_' + value).className += ' active';
           $scope.$apply();
        };

当前按钮的背景颜色确实突出显示,但仅在单击屏幕其他位置后才会突出显示。换句话说,它不会像它应该的那样立即更新。

任何想法如何纠正这个问题?

标签: angularjs

解决方案


如果没有看到更多代码或现有问题的重现,很难诊断问题。但是,从上面看,你肯定不是在做“angularjs”的方式。更角度的方法是使用绑定并在用户单击不同的按钮选项时更新模型。一个非常基本(且风格丑陋)的示例:

angular.module('myApp', [])
  .controller('MainController', function () {
    var self = this;
    
    self.$onInit = function $onInit() {
      // These will be ng-repeated over for the example
      self.buttons = [
        'Option 1',
        'Option 2',
        'Option 3'
      ];

      // This is the model binding that will drive the active style
      self.activeIndex = 0;
    };
    
    self.setActiveIndex = function setActiveIndex(index) {
      // This is called on button click and updates the model used
      // for the active button styling
      self.activeIndex = index;
    };
  });
.active {
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!-- repeat the buttons. when clicked, call controller method to update model's active index -->
<div ng-app="myApp" ng-controller="MainController as $ctrl">
  <button ng-repeat="b in $ctrl.buttons" type="button" ng-class="{active: $ctrl.activeIndex===$index}" ng-click="$ctrl.setActiveIndex($index)">{{::b}}</button>
</div>

外卖:

  • 您可能不应该进行 DOM 操作。使用现有的指令和模型绑定,否则您将失去许多应该从 angularjs 获得的好处。
  • 不要调用 $scope.$apply()。如果您在模板中使用 ng-click(您可能应该这样做,而不是自己构建事件侦听器),Angular 将为您执行此操作。

推荐阅读