对,所以我发现了这个 jsfiddle,它确实帮助我在不使用漂亮的复选框插件的情况下解决问题:
http://jsfiddle.net/evaneus/z9rge/
正如詹姆斯在他的回答中提到的那样,指令需要访问控制器:
angular.module('buttonToggle', []).directive('buttonToggle', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, element, attr, ctrl) {
var classToToggle = attr.buttonToggle;
element.bind('click', function() {
var checked = ctrl.$viewValue;
$scope.$apply(function(scope) {
ctrl.$setViewValue(!checked);
});
});
$scope.$watch(attr.ngModel, function(newValue, oldValue) {
newValue ? element.addClass(classToToggle) : element.removeClass(classToToggle);
});
}
};
});
<p>
<input id="gradeCheck" type="checkbox" ng-model="myModel['A']"> A
<input type="checkbox" ng-model="myModel['B']"> B
<input type="checkbox" ng-model="myModel['C']"> C
<input type="checkbox" ng-model="myModel['D']"> D
</p>
<p>
<button button-toggle="active" class="btn" ng-model="myModel['A']">A</button>
<button button-toggle="active" class="btn" ng-model="myModel['B']">B</button>
<button button-toggle="active" class="btn" ng-model="myModel['C']">C</button>
<button button-toggle="active" class="btn" ng-model="myModel['D']">D</button>
</p>
然后我只需要按照我想要的方式设置按钮的样式,无论是否有活动样式,并且所有工作都很好:)