我希望有一些Angular 1.x专家可以告诉我我做错了什么。我有一个简单的功能来更新“选项卡组”中的3个按钮中的哪个是当前按钮。只要单击任意一个按钮,就会调用此函数。
$scope.updateFilter = function (type, value) {
// Additional unrelated code here ...
document.getElementsByClassName('active')[0].className = document.getElementsByClassName('active')[0].className.replace(' active', '');
document.getElementById('tabButton_' + value).className += ' active';
$scope.$apply();
};
当前按钮的背景色确实突出显示,但是只有在屏幕上其他位置单击一下之后。换句话说,它不会立即更新。
有什么想法可以纠正这个问题吗?
答案 0 :(得分:2)
如果不查看更多代码或复制现有问题,就很难诊断问题。但是,从上面来看,您肯定没有采用“ angularjs”方式。更具角度的方法是使用绑定并在用户单击不同的按钮选项时更新模型。一个非常基本(且样式丑陋)的示例:
angular.module('myApp', [])
.controller('MainController', function () {
var self = this;
self.$onInit = function $onInit() {
// These will be ng-repeated over for the example
self.buttons = [
'Option 1',
'Option 2',
'Option 3'
];
// This is the model binding that will drive the active style
self.activeIndex = 0;
};
self.setActiveIndex = function setActiveIndex(index) {
// This is called on button click and updates the model used
// for the active button styling
self.activeIndex = index;
};
});
.active {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!-- repeat the buttons. when clicked, call controller method to update model's active index -->
<div ng-app="myApp" ng-controller="MainController as $ctrl">
<button ng-repeat="b in $ctrl.buttons" type="button" ng-class="{active: $ctrl.activeIndex===$index}" ng-click="$ctrl.setActiveIndex($index)">{{::b}}</button>
</div>
外带: