jquery - Angular 和 jQuery 打起来了

标签 jquery html angularjs

最近我决定将我的 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();
    });
 }]);

JSBin:http://jsbin.com/latobi/edit?html,js,output

关于jquery - Angular 和 jQuery 打起来了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225376/

相关文章:

Angularjs 搜索引擎优化问题

jquery - 为什么 "done"或 "fail"jQuery AJAX 回调都不在 HTTP 500 上执行?

php - 将JavaScript数组数据插入MySQL数据库的问题

html - 如何在 HTML img 标签中屏蔽图像?

Javascript $q Promise 请求覆盖还是堆栈?

java - 如何从 angularjs 调用 Java Controller 类

javascript - 类似于 Facebook 评论框的富文本框

jQuery-File-Upload - TypeError : $(. ..).fileupload 不是函数

javascript - HTML5 Canvas 成长圈

javascript - 单击时如何使我更改为另一个图像的图像?