2014-10-27 64 views
0

的乘法我有,我不明白为什么我的功能被更频繁地叫了很多以下(简化)例如然后我NG重复呈现的内容调用。 (代码显示的问题比我可以解释的更好)。搞不清楚为什么我的功能得到由NG-重复

(我没有读到NG-重复启动/ NG-重复结束,但我看不出这怎么会在这里帮助我。)

预先感谢任何帮助的投入!

<table> 
<tr> 
    <th><strong>Date</strong></th> 
    <td ng-repeat="day in days"> 
    <!-- Where days is an array containing 6 dates --> 
     {{day | date : 'EEE d'}} 
    </td> 
</tr> 

<tr> 
    <th><strong>Participants</strong></th> 
    <td ng-repeat="day in days"> 
     <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
     <!-- This gets rendered 6 times but the function userParticipates() gets called 36 times (6*6?) - Why is that the case?--> 
    </td> 
</tr> 

更新

谢谢您的回答,Woot4Moo! 对不起,我仍然困惑:

你说我的代码生成此:

<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 

但是那其实不是我所看到的。我有'用户不参与'每行只有一次(6次)。它只是ng中的函数,如果它被调用了36次。我不明白为什么,因为我的重复似乎没有嵌套到另一个...?

回答

3

由于ng-if条件启动了$ watch,所以您不知道将调用多少次,但是您可以放心,它会被称为很多,并且每个方法将在摘要循环中被多次调用。每当页面路由发生变化或者页面上的任何事件(AJAX完成,按钮点击等等)时,都会触发摘要循环。典型的摘要循环将贯穿每个手表至少两次(一次用于初始更改,一次时间确认没有进一步的变化)。注册$ watch本身也会导致额外的通话。

这不是非典型这样的表述在应用的过程中进行评估的时间100S或1000。

如果你的函数做任何事情,除了一个简单的健康检查一样a == b那么你应该计算结果和缓存它。例如,在你的控制器,你可以对用户id一个$手表那么当用户id更改,需设置currentUserParticipating = userParticipates(userId),然后你会在你的NG-如果使用currentUserParticipating。

+0

这说明它更新了!也是好的建议,让控制器努力工作,只将boolean等同于HTML!谢谢! – Riscie 2014-10-27 20:33:22

1

它确实是因为每一天(在你的例子中有6)它生成此HTML:

<span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 

你有效地希望这样的:

<div ng-repeat="day in days"> 
     <td> 
      <span ng-if="!userParticipates(1)"><a href="">User does not participate</span> 
    </div> 
     </td> 

https://stackoverflow.com/a/18156912/205426

<table> 
    <tbody ng-repeat="obj in rows"> 
     <tr ng-repeat="e in obj.row"> 
      <td>{{e}}</td> 
     </tr> 
     <tr> 
      <td colspan="4">{{obj.description}}</td> 
     <tr> 
    </tbody> 
</table> 
0

不要以为NG-重复的for循环。 Ng-repeat会根据需要在摘要循环中多次调用函数,而不是每个项目一次。模型变量分配到NG-IF,并在控制器

相关问题