我目前正在将一些旧指令重写为新的组件语法。我的一个指令需要在 DOMnode 上切换一个类。
<my-directive ng-class="$ctrl.getClassList()">
<!-- DIRECTIVE CONTENT -->
</my-directive>
现在,当我将其转换为组件时,此功能不再起作用。是否有一些我没有找到的新功能?或者这根本不再可能?
<my-component ng-class="$ctrl.getClassList()">
<!-- COMPONENT CONTENT -->
</my-component>
感谢您抽出宝贵的时间!
要查看完全工作(或更好,不工作)的示例,您可以查看此代码段,或前往Plunkr
(function(angular) {
angular.module('plunker', []);
})(angular);
// DIRECTIVE
(function(angular) {
angular
.module('plunker')
.controller('MyDirectiveController', [function() {
this.cssClass = '';
this.toggle = function() {
this.cssClass = (this.cssClass === '') ? 'active' : '';
}
}])
.directive('myDirective', [function() {
return {
scope: true,
restrict: 'E',
controller: 'MyDirectiveController',
controllerAs: '$ctrl',
template: '<button ng-class="$ctrl.cssClass" ng-click="$ctrl.toggle()">hit me baby one more time</button>'
};
}]);
})(angular);
// COMPONENT
(function(angular) {
angular
.module('plunker')
.controller('MyComponentController', [function() {
this.cssClass = '';
this.toggle = function() {
this.cssClass = (this.cssClass === '') ? 'active' : '';
}
}])
.component('myComponent', {
controller: 'MyComponentController',
template: '<button ng-class="$ctrl.cssClass" ng-click="$ctrl.toggle()">Do it again</button>'
});
})(angular);
my-directive,
my-component {
display: block;
padding: 1em;
border: 1px solid transparent;
transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0;
}
my-directive.active,
my-component.active {
padding: 1em;
font-size: 2em;
background: red;
color: white;
border-color: darkred;
border-width: 2px;
}
my-directive.active button,
my-component.active button {
transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0;
border: 1px solid;
font-size: inherit;
color: inherit;
border-color: inherit;
background: inherit;
}
button.active {
text-decoration: underline;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.7/angular.js" data-semver="1.5.7"></script>
</head>
<body>
<my-directive ng-class="$ctrl.cssClass"></my-directive>
<my-component ng-class="$ctrl.cssClass"></my-component>
</body>
</html>