Angular和jQuery陷入了战斗

时间:2015-08-26 11:26:41

标签: 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函数,通过运行list-view__body来检查$(element).length内的行数。这仍然保持返回0,所以按钮没有调整大小。我已尝试对此设置延迟,但它仍然返回0.现在,我知道这与DOM,Angular和jQuery有关。我该怎么办?

1 个答案:

答案 0 :(得分:1)

由于我们没有看到您的代码,我只能猜测。 我认为这是因为你的jQuery函数在AngularJS完成其摘要周期之前被调用。当发生这种情况时,ng-repeat还没有完成它的工作,并且长度返回零。你可以做的是将调用你的jQuery函数移动到你的Angular控制器并用$ 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