有人能帮我解释一下为什么我的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;
};
}发布于 2015-06-05 03:25:19
在您的场景中,只有几件事是错误的。
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我的变量在它不知情的情况下发生了变化。
https://stackoverflow.com/questions/28956357
复制相似问题