如果快速切换,ng类在绑定变量上不能很好地工作,这可能吗

ng-class not working well on the binding variable if toggled quickly, Is that possible?

本文关键字:工作 很好 不能 绑定 ng 如果 变量      更新时间:2023-10-14

我面临以下问题:

<input 
    type = "text" 
    class = "class1 class2" 
    placeholder = "Type here..." 
    autocomplete = "off" 
    ng-model = "searchKeyword" 
    name = "searchId"
    ng-class = "{'my-class1': myObject.myAttribute,'my-class2': myObject.myFunction()}" //<-- HERE IS THE PROBLEM
    ng-disabled = "myObject.myFunction()"
    ng-change = "searchConditionChanged()" numbers-only />

大多数情况下,myObject.myFunction()会返回false,但也有很短的一段时间会返回true。

在我的网页上,我可以看到类"my-class2"被正确地添加到<input>中,但在那之后,当myObject.myFunction()再次返回false时,该类应该被删除。

但问题是,为什么添加了"my-class2"类,却没有删除。当我在console.log()中看到函数返回false时,该类仍在DOM树中。

即使我使用$scope.$apply()$scope.$digest()强制更新,它也不会改变。

类"my-class1"绑定到myObject.myAttribute。它也有同样的问题。

另一件让我很困惑的事情是,当myObject.myFunction()返回true的时间稍长(比如500ms)时,ng类总是正确地设置类。

感谢您的帮助!

我想问题在于如何编写代码,粘贴控制器或方法的最佳方式;我认为这样做可能会造成这个问题:

  1. 在你的代码中,你只在开始时间表演我的课,然后永远不会行动
  2. 你的代码可能太复杂,周期太长
  3. 您更改了值,但不绑定到视图

我的例子很好

		var app = angular.module('myApp', []).controller('haha', function ($scope, $timeout) {
			$scope.user = {
				name: 'admin'
			};
			$timeout(function loop() {
					if ($scope.user.name) {
						$scope.user.name = '';
						console.log($scope.user.name);
					} else {
						$scope.user.name = 'admin';
						console.log($scope.user.name);
					}
					$timeout(loop, 5)
				}, 5)
		})
.r {
			color: red;
			font-size: 30px;
		}
		
      
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="haha">
		<div ng-class="{'r':user.name}">{{user.name}}</div>
</div>

相关文章: