简体   繁体   English

Angular ng-class没有更新

[英]Angular ng-class isn't updating

Can someone help me understand why my ng-click doesn't update the class? 有人可以帮我理解为什么我的ng-click不能更新课程吗?

heading.onClick() updates the controller's isOpen attribute. heading.onClick()更新控制器的isOpen属性。 When it is false, the class does not remove the collapsed attribute. 如果为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;
    };
}

In your scenario, there are just a couple things wrong. 在您的情况下,只有几处错误。

  1. Your quotes might need to be escaped since you are alternating between single and double a few times, or you might need to use template instead of templateUrl 您可能需要将引号转义,因为您要在单次和两次之间交替几次,或者您可能需要使用template而不是templateUrl

  2. If you are using angular 1.3+, instead of assigning self to this you can use the scope: true property, and use 'this'. 如果您使用的是angular 1.3+,则可以使用scope:true属性,并使用'this',而不是为此分配self。

 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> 

In your case, you probably won't need to worry about this, but I have run across a scenario where I had to call $scope.$apply() (or this.$apply()) to notify angular that my variable has changed without its knowledge. 在您的情况下,您可能不必担心这一点,但是我遇到了不得不调用$ scope。$ apply()(或this。$ apply())以通知angular我的变量具有在没有知识的情况下发生了变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM