Angular ng-class没有更新

Angular ng-class isn't updating

本文关键字:更新 ng-class Angular      更新时间:2023-09-26

有人可以帮助我理解为什么我的ng-click不更新类吗?

heading.onClick()更新控制器的isOpen属性。当它为 false 时,类不会删除 collapsed 属性。

 .... (this is inside a controller aliased `heading`)
 <div ng-class="{'collapsed': !heading.isOpen}" ng-click="heading.onClick()"></div>

directive:
...
templateUrl: '/that/code/above',
controllerAs: 'heading',
controller: function(){
    var self = this;
    self.isOpen = false;
    self.onClick = function(){
        self.isOpen = !self.isOpen;
    };
}

在你的方案中,只有几件事是错误的。

  1. 您的引号可能需要转义,因为您正在交替在单和双之间几次,或者您可能需要使用模板而不是模板URL

  2. 如果您使用的是角度 1.3+,而不是将自己分配给它,而是将自己分配给它可以使用 scope: true 属性,并使用"this"。

function myDirective() {
  return{
    restrict: 'AE',
    template: "<div ng-class='{'"collapsed'": !heading.isOpen}' ng-click='heading.onClick()'>Click on me</div>",
    scope: true,
    controller: function(){
                   this.isOpen = false;
                   this.onClick = function(){
                   this.isOpen = !this.isOpen;
                        
                        // in some situations you might need to call $apply() to get it to digest changes.
                        // for example if you change isOpen through a non-angular click angular wouldn't know
                        // to update the class until you call this.$apply()
                        
                        //this.$apply();
                   };
      
    },
    controllerAs: 'heading'
      
    };
  }
var app = angular.module('app', [])
                 .directive('myDirective', [myDirective]);
.collapsed {
  color: red;
}
<!DOCTYPE html>
<html >
  <head>
    <link rel="stylesheet" href="style.css">        
  </head>
  <body ng-app="app">
     <my-directive></my-directive>  
     
     <script src="https://code.angularjs.org/1.4.0/angular.js"></script>
     <script src="script.js"></script>
  </body>
</html>

在您的情况下,您可能不需要担心这一点,但我遇到了一个场景,我不得不调用 $scope.$apply()(或 this.$apply()) 来通知 angular 我的变量在它不知情的情况下发生了变化。