2016-03-19 5 views
0

У меня есть базовое понимание цикла дайджеста Углового, но я смущен, почему этот конкретный метод выполняется несколько раз. Вот что в моем контроллере:Проблема с угловым неидемпотентным методом

initializePage(); 
    function initializePage() { 
     var promise = getPageInfo(); 
     promise.then(function() { 
      $scope.dataLoading = true; 
     }) 
    }; 
    function getPageInfo() { 
     var deferred = $q.defer(); 
     deferred.resolve(lwsService.getLWSpageinfo() 
     .success(function (data) { 
      $scope.company = data.ContractorInfo; 
      $scope.img = base64ArrayBuffer($scope.company.imgCompanyLogo); 
      $scope.incompleteInfo = data.IncompleteInfo; 
      $scope.sections = data.QuestionSections; 
      $scope.verifications = data.Verifications; 
      $scope.subscriptions = data.SubscriptionInfo; 
      $scope.user = data.UserInfo; 
      $scope.ssqstatus = data.SSQStatus; 
      $scope.ssqdetails = data.SSQDetail[0]; 
      $scope.completionInfo = data.CompletionInfo[0]; 
      $scope.states = data.States; 
      $scope.countries = data.Countries 
      $scope.completionInfo.dteDateSSQLastUpdated = convertDate($scope.completionInfo.dteDateSSQLastUpdated); 
        return deferred.promise; 
    }; 

Вот мой HTML:

<div ng-app-="myModule" ng-controller="LWSCtrl"> 
<div cg-busy="waitopr"></div> 
<tabset> 
    <tab heading="Dashboard"> 
     <div ng-repeat="m in majors"> 
      <div ng-controller="LWSCtrl"> 
       <accordion close-others="oneAtATime"> 
        <accordion-group is-open="status.open"> 
         <accordion-heading> 
          <div style="height:20px"> 
           <span class="pull-left">{{m.MajorName}}</span><i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-up': status.open, 'glyphicon-chevron-down': !status.open}"></i> 
          </div> 
         </accordion-heading> 
         <div class="panel panel-default"> 
          <div class="panel-body"> 
           <table style="border:none; width:100%"> 
            <tr> 
             <td style="border:none"> 
              <div class="newWidget"> 
               <div class="WidgetTitle" style="width:100%; color:white" ng-style="{'background-color': m.header.WidgetStateBackgroundColor}">{{m.header.WidgetTitleText}}</div> 
               <div style="padding-left:10px; padding-top:10px"> 
                <ul class="grid-wrap one-whole plain"> 
                 <li ng-repeat="item in m.items" class="grid-col one-quarter"> 
                  <div ng-switch="item.IsModuleWordingFixed"> 
                   <div ng-switch-when="false"> 
                    <div ng-switch="item.vchGraphic"> 
                     <div ng-switch-when="images/ContractorRankingWidget/green.png"> 
                      <span style="display:inline-block; cursor:pointer" data-toggle="modal" data-target="#scoreOverride" ng-value="scoredetails" ng-click="Override(scoredetails)" ng-model="score.details" class="dashboard-button-green">{{item.ModuleCurrentStateText}}</span><span style="display:inline-block; font-weight:bolder; vertical-align:middle"> &nbsp; &nbsp;{{item.ModuleHeaderText}}<br />&nbsp;</span> 
                     </div> 
                     <div ng-switch-when="images/ContractorRankingWidget/red.png"> 
                      <span style="display:inline-block; cursor:pointer" data-toggle="modal" data-target="#scoreOverride" ng-value="scoredetails" ng-click="Override(scoredetails)" ng-model="score.details" class=" dashboard-button-red">{{item.ModuleCurrentStateText}}</span><span style="display:inline-block; font-weight:bolder; vertical-align:middle"> &nbsp; &nbsp;{{item.ModuleHeaderText}}<br /></span> 
                     </div> 
                     <div ng-switch-when="images/ContractorRankingWidget/yellow.png"> 
                      <span style="display:inline-block; cursor:pointer" data-toggle="modal" data-target="#scoreOverride" ng-value="scoredetails" ng-click="Override(scoredetails)" ng-model="score.details" class="dashboard-button-yellow">{{item.ModuleCurrentStateText}}</span><span style="display:inline-block; font-weight:bolder; vertical-align:middle"> &nbsp; &nbsp;{{item.ModuleHeaderText}}<br /> &nbsp;</span> 
                     </div> 
                    </div> 

                   </div> 
                   <div ng-switch-when="true"> 
                    <span style="display:inline-block; cursor:pointer" data-toggle="modal" data-target="#moduleOverride" ng-value="item" ng-click="moduleOverride(item)"><img ng-src="~/{{item.vchGraphic}}" /></span><span style="display:inline-block;vertical-align:middle"> &nbsp; &nbsp;<span style="font-weight:bolder">{{item.ModuleHeaderText}}</span><br /> &nbsp; &nbsp;{{item.ModuleCalculatedStateText}}</span> 
                    <div>&nbsp;</div> 

                   </div> 
                  </div> 
                 </li> 
                </ul> 
               </div> 
              </div> 
             </td> 
             <td style="border:none"> 
              <table style="border:none"> 
               <tr ng-repeat="text in m.Legend"> 
                <td style="border:none" class="LegendImage" ng-style="{'background-color': text.BackGroundColor}">&nbsp;</td> 
                <td style="border:none; padding:3px">{{text.WidgetStateText}}<br /></td> 
               </tr> 
               <tr style="border:none" ng-if="overridden || moduleoverridden"> 
                <td style="border:none"><img src="~/Images/ContractorRankingWidget/override.png" /></td> 
                <td style="border:none">Override</td> 
               </tr> 

              </table> 
             </td> 
            </tr> 
           </table> 
          </div> 
         </div> 
        </accordion-group> 
       </accordion> 
      </div> 
     </div> 
    </tab> 
    <tab heading="SSQ Information"> 
     <div class="panel panel-default"> 
      <div class="panel-body"> 
       <div ng-switch="expired"> 
        <div ng-switch-when="true"> 
         <span style="display:inline-block" class="calendar-background-red"><img src="~/Images/calendar_icon.png" /></span><span style="display:inline-block"><span style="font-weight:bold"> &nbsp; &nbsp; Subscription Expiration Date</span><br /> &nbsp; &nbsp; {{subscriptions.dteExpiresWithGracePeriod}}</span><span class="float-right"></span> 
        </div> 
        <div ng-switch-when="false"> 
         <span style="display:inline-block" class="calendar-background-green"><img src="~/Images/calendar_icon.png" /></span><span style="display:inline-block"><span style="font-weight:bold"> &nbsp; &nbsp; Subscription Expiration Date</span><br /> &nbsp; &nbsp; {{subscriptions.dteExpiresWithGracePeriod}}</span><span class="float-right"></span> 
        </div> 
       </div> 
       <br /><br /> 
       <div style="padding-left:10px;padding-right:10px"> 
        <table style="width:100%"> 
         <thead> 
          <tr style="background-color:#003a5d; color:white"> 
           <th colspan="5"> 
            SSQ Status 
           </th> 
          </tr> 
          <tr style="background-color:#b4001a; color:white"> 
           <th colspan="5"> 
            <div ng-switch="ssqstatus"> 
             <div ng-switch-when="false"> 
              Incomplete 
             </div> 
             <div ng-switch-when="true"> 
              Complete 
             </div> 
            </div> 
           </th> 
          </tr> 
          <tr style="background-color:#cfe7f1; text-align:center"> 
           <th>SSQ Last Edited By</th> 
           <th style="text-align:center">Date Edited</th> 
           <th style="text-align:center">Last Incident QTR Reported</th> 
           <th style="text-align:center">Number of Employees</th> 
           <th style="text-align:center">Number of Active Instructors</th> 
          </tr> 
         </thead> 
         <tbody> 
          <tr> 
           <td>{{completionInfo.CompletedByUserName}}</td> 
           <td style="text-align:center">{{completionInfo.dteDateSSQLastUpdated}}</td> 
           <td style="text-align:center">{{ssqdetails.vchLastCompleteQuarter}}</td> 
           <td style="text-align:center">{{ssqdetails.intAvgNumEmployees}}</td> 
           <td style="text-align:center">{{ssqdetails.ActiveInstructorCount}}</td> 
          </tr> 
          <tr style="background-color:#cfe7f1"> 
           <td colspan="5"> 
            Reason of Status:&nbsp;{{completionInfo.IncompleteReason}} 
           </td> 
          </tr> 
          <tr ng-repeat="info in incompleteInfo"> 
           <td style="text-decoration:underline;color:blue;text-align:left;cursor:pointer" ng-value="info.QuestionSectionID" ng-click="viewIncomplete(info.QuestionSectionID)">View</td> 
           <td colspan="4">{{info.vchSectionName}}</td> 
          </tr> 
         </tbody> 
        </table> 
       </div> 
      </div> 
     </div> 
    </tab> 
    <tab heading="Questionnaire"> 
     <div class="panel panel-default"> 
      <div class="panel-body"> 
       <table style="width:100%; border:dotted 1px"> 
        <thead> 
         <tr style="background-color:#003a5d; color:white;font-weight:bold"> 
          <th colspan="3" style="padding-left:10px">Questionnaire</th> 
         </tr> 
         <tr style="background-color:#cfe7f1"> 
          <th style="padding-left:10px; width:60%">SSQ Section</th> 
          <th style="text-align:center; width:20%">Completion</th> 
          <th style="text-align:center; width:20%">Print Selection</th> 
         </tr> 
        </thead> 
        <tbody> 
         <tr ng-repeat="section in sections" style="border-bottom:dotted 1px"> 
          <td style="text-decoration:underline; color:blue; cursor:pointer" ng-model="section" data-toggle="modal" data-target="#stack1" ng-click="viewSection(section)">{{section.vchSectionName}}</td> 
          <td style="border-left:dotted 1px"> 
           <div ng-switch="section.bitSectionCompleted"> 
            <div ng-switch-when="true"> 
             <div style="color:green; text-align:center" ng-bind-html="section.bitSectionCompleted | applyMarks | trustedhtml"></div> 
            </div> 
            <div ng-switch-when="false"> 
             <div style="color:red; text-align:center" ng-bind-html="section.bitSectionCompleted | applyMarks | trustedhtml"></div> 
            </div> 
           </div> 
          </td> 
          <td style="text-align:center; border-left:dotted 1px"><input type="checkbox" checklist-model="getSections()" checklist-value="section" ng-change="printSelection(section, checked)" /></td> 
         </tr> 
        </tbody> 
       </table> 
       <br /> 
       <div cg-busy="loadingSections">@* *@</div> 
       <div class="float-right"><button type="button" class="btn btn-info" style="width:200px" ng-click="selectAll()">Select All</button>&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-info" style="width:200px" ng-click="unselectAll()">Unselect All</button></div><br /><br /> 
       <div class="float-right"><button type="button" class="btn btn-primary" style="width:200px" data-toggle="modal" data-dismiss="modal" data-target="#stack4" ng-disabled="dataLoading" ng-click="printSections()">Print 

Selected</button></div> 

       </div> 
      </div> 
     </tab> 
    </tabset> 

Я попытался с помощью оператора двойного двоеточия, но это не помогло. Я смущен тем, что мне нужно изменить или как изменить это, чтобы сделать его идемпотентным. Служба делает звонок в наш веб-api (который он звонит около 4 раз). Он возвращает много данных, поэтому их выполнение выполняется много раз, перетаскивая мое приложение в обход. Любая помощь по улучшению этого кода очень ценится.

ответ

2

У вас есть экземпляр контроллера на внешнем уровне приложения, но также создают дополнительные экземпляры внутри ng-repeat:

<div ng-repeat="m in majors"> 
     <div ng-controller="LWSCtrl"> 

Это означает, что свежий контроллер создается для каждого вхождения m и в любое время, когда значение майоров изменится, у вас будет больше контроллеров, созданных и/или уничтоженных.

Возможно, это не то, что вы намеревались, я бы подумал, что одного экземпляра контроллера будет достаточно.

+0

Это имеет смысл. Я добавил контроллеры, потому что без них аккордеоны в ng-repeat не работали отдельно. Думаю, я должен попытаться найти другой способ заставить аккордеоны работать независимо. Отдельные экземпляры контроллера - все, что я мог придумать, чтобы решить эту проблему. Большое спасибо за Вашу помощь. Это меня озадачило. –

+0

@ RaniRadcliff вы действительно можете захотеть, чтобы отдельные контроллеры обрабатывали гармоники, но в этом случае выполняйте другой контроллер, который просто делает аккордеон. Или вы можете просто захотеть несколько методов в своем основном контроллере и перейдите в 'm' или' $ index' из повтора. – Duncan

Смежные вопросы