angular.js - angualrJs 重置 表格 的 ng-class 不起作用

浏览:23日期:2022-12-30

问题描述

先拜谢大神们过来看问题!!!先拜谢大神们过来看问题!!!先拜谢大神们过来看问题!!!本人在做一个后台系统时,需要点击 td 时做些操作,如给 td 添加class,页面上有个按钮要对表格进行重置,即去掉 td 上的class。代码如下:

html:

<!DOCTYPE html><html lang='en' ng-app='myApp'><head> <meta charset='UTF-8'> <title>Document</title> <link rel='stylesheet' href='https://www.6hehe.com/wenda/styles/bootstrap.min.css'> <style> .selected {background: #139029;} </style></head><body ng-controller='myCtrl'> <p class='container-fluid'><table class='table table-bordered table-striped'> <thead><tr> <th>item1</th> <th>item2</th> <th>item3</th></tr> </thead> <tbody><tr ng-repeat='row in [1,2,3]'> <td ng- ng-repeat='item in tableData' my-td >{{item}}</td></tr> </tbody></table><button ng-click='reset();'>重置表格</button> </p></body><script src='https://www.6hehe.com/wenda/lib/angular.1.5.5.min.js'></script><script src='https://www.6hehe.com/wenda/lib/jquery.2.2.2.min.js'></script><script src='https://www.6hehe.com/wenda/src/resetTable.js'></script></html>

resetTable.js 部分:

var myApp = angular.module(’myApp’,[]); myApp.controller(’myCtrl’,[’$scope’,function($scope){ $scope.tableData = [’hello’,’blue’,’angular’]; //$scope.selectClass = true; //设置 ture 可以 但只有第一次可以 $scope.reset = function(){ console.log(’reset’); $scope.selectClass = false;}}]).directive(’myTd’,function(){return { restrict : ’A’, link : function(scope,elem){$(elem).on(’click’,function(){ if($(this).hasClass(’selected’)){$(this).removeClass(’selected’) }else{$(this).addClass(’selected’); }}) }} });

点击重置,$scope.selectClass=false 不起作用,求大神说明原因,有没有遇到同样问题的??

(后来我,通过 给按钮定义个指令,在指令中将td的class清除,但感觉这种方式不太好,非常想知道为啥 $scope.selectClass = false 的方式不行)

问题解答

回答1:

这几天做了个小型系统的项目,在项目中 加载 loading 效果是获得启发,实现了该效果,感觉比较理想,不知道是不是最优方案,也欢迎小伙伴们继续补充。我的解决方法如下:

myApp.controller(’myCtrl’,[’$scope’,’$rootScope’,function($scope,$rootScope){ $scope.tableData = [’hello’,’blue’,’angular’]; $scope.reset = function(){console.log(’reset’);$rootScope.$broadcast(’resetTable’); };}]).directive(’myTd’,function(){ return {restrict : ’A’,link : function(scope,elem){ $(elem).on(’click’,function(){if($(this).hasClass(’active’)){ $(this).removeClass(’active’);}else{ $(this).addClass(’active’);} }); scope.$on(’resetTable’,function(){$(’.table td’).removeClass(’active’); });} };});回答2:

demo

写了个简单的,没什么问题。

相关文章: