最近我决定将我的 webapp 切换到 AngularJS。虽然我有很多遗留的 jQuery 代码,所以理想情况下我想并排使用它们。一切都很顺利,但是昨天他们两个吵架了。
我的应用程序中有一个 ng-repeat
,但在此列表中有一个 jQuery 脚本可以根据设备和浏览器将所有按钮的大小调整为特定大小。
这是 html:
<div class="list-wrapper">
<table>
<thead>
<tr>
<th>Restaurant</th>
<th>Location</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody class="list-view__body">
<tr ng-repeat="restaurant in restaurants">
<td>{{ restaurant.name }}</td>
<td>{{ restaurant.location }}</td>
<td>{{ restaurant.status }}</td>
<td>{{ restaurant.actions }}</td>
</tr>
</tbody>
</table>
</div>
我有一个 jQuery 函数,它通过运行 $(element).length
检查 list-view__body
中有多少行。虽然它一直返回 0,因此按钮没有调整大小。我已经尝试为此设置延迟,但它仍然返回 0。现在,我明白这与 DOM
、Angular 和 jQuery 有关。我该怎么办?
最佳答案
由于我们没有看到您的代码,所以我只能猜测。 我假设发生这种情况是因为在 AngularJS 完成其摘要周期之前调用了 jQuery 函数。当发生这种情况时,ng-repeat 还没有完成它的工作并且长度返回零。你可以做的是将对 jQuery 函数的调用移动到 Angular Controller 中,并用 $timeout 包装它,如下所示:
angular.module('myHappyApp',[])
.controller('MyHappyController',['$timeout', function($timeout){
this.restaurants=[
{
name:'Burger land',
location: 'Chicago',
status:'awesome',
actions: 'go there'
},
{
name:'Pizzamania',
location:'Shanghai',
status:'wicked',
actions:'eat all the pizza!'
}
];
$timeout(function(){
myHappyJqueryFunction();
});
}]);
关于jquery - Angular 和 jQuery 打起来了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225376/