двусторонняя привязка не работает даже с точечной нотацией - PullRequest
0 голосов
/ 14 января 2019

Я начинаю с AngularJS и использую переменную контроллера для навигации по массиву вопросов, и она работает при использовании функции nextQuestion, индекс обновляется, и следующий вид отображается в представлении, но если я пытаюсь получить одинаковое значение (индекс) в другой функции, всегда возвращает 0.

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

Мой контроллер:

myApp.controller('SurveyController',['$scope','$http', '$location','$routeParams','surveyMetrics','DataService',function($scope,$http, $location,$routeParams,surveyMetrics,DataService){
    console.log('LOADED QUIZ CONTROLLER');
      var vm = this;
      vm.scope = {
        index: 0
      };
      vm.surveyMetrics = surveyMetrics;
      vm.surveyQuestions = DataService.surveyQuestions;
      vm.DataService = DataService;

      /*
      vm.getQuestions = function(){
          $http.get('/api/questions').then(function(response){
          $scope.questions = response.data;
        });  
      }
      */

      /*
      vm.activateSurvey = function(){
        surveyMetrics.changeState(true);
      }
      */
     vm.getCurrentIndex = function(){
       return vm.scope.index;
     }

      vm.nextQuestion = function () {
        console.log('NEXT QUESTION!');
        console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);
        var currentIndex = vm.getCurrentIndex();
        var newIndex = currentIndex+1;
        scope = {};

        if (currentIndex == vm.surveyQuestions.length) {
          newIndex = vm.surveyQuestions.length -1;
        }

        vm.scope.index = newIndex;
        console.log('Inside Object: '+vm.scope)
        console.log('vm.index'+vm.scope.index); 
        console.log('vm.indexFunction'+vm.getCurrentIndex());
      }

      /*
      vm.previousQuestion = function () {
        console.log('PREVIOUS QUESTION!');
        console.log('NUMBER OF QUESTIONS: '+ vm.surveyQuestions.length);

        if (vm.scope.index == 0) {
          vm.scope.index = 0;
        }else{
          vm.scope.index--;
        }

      }
      */
      vm.activeSurveyQuestion = function(questionId,index){
        console.log('question id and index',questionId,index);
        if (questionId == index) {
          var navBtn = document.getElementById('navBtn_'+index);
          navBtn.classList.add('active');
        }
      }


      vm.navigateSurvey = function () {

          var answerPane = document.getElementById('answer-pane');

          document.onkeydown = function (e) {
            console.log('INSIDE KEYDOWN: ')
            e.preventDefault();

            var pressedKey = e.keyCode;
            console.log('PRESSED KEY IN SURVEY: ' + pressedKey);

            if (pressedKey === rightArrow) {
              console.log('survey - right arrow pressed');
              document.getElementById('nextQuestionBtn').click();

              console.log('FUCKING INDEX FML!: '+vm.getCurrentIndex()+' | '+vm.scope.index);
              var questionType = DataService.getQuestionType(vm.scope.index);
              console.log('Survey Controller: question type:  '+questionType);
            }
            if (pressedKey === leftArrow) {
              console.log('survey - left arrow pressed');
              document.getElementById('previousQuestionBtn').click();


            }
(...)
My View:
 <!--Satisfaction Survey-->
    <div ng-controller="SurveyController as survey" ng-init="survey.getSurvey();">
      <!-- 
        <p ng-repeat="question in survey.surveyQuestions" ng-show ="survey.surveyMetrics.surveyActive">
          {{question.question}}
        </p>
      -->
        <!--Survey Modal -->
      <div class="modal fade" id="surveyModal" role="dialog">
        <div class="modal-dialog">

          <!-- Modal content-->
          <div class="modal-content">
              <div class="text-center"> Customer Satisfaction Survey</div>
            <div class="modal-header">

              <h4 class="modal-title">{{survey.surveyQuestions[survey.getCurrentIndex()].question}}</h4>
            </div>
            <div class="modal-body survey" id="answer-pane">
              <div class="row">
                    <div class="col-sm-2 survey-left-arrow" ng-click="survey.previousQuestion();" id="previousQuestionBtn">
                     <p>&#8249;</p>
                    </div>

                    <div class="col-sm-8">
                      <!-- <p ng-repeat="answer in survey.surveyQuestions[survey.index].answers">{{answer}}</p> --> 
                      <p ng-repeat="answer in survey.surveyQuestions[survey.getCurrentIndex()].answers">
                        <button type="button" class="btn" id="answerId_{{survey.getCurrentIndex()}}"
                                ng-class="{'survey-check-box': (survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'),
                                           'survey-btn_{{($index+1)}}': (survey.surveyQuestions[survey.getCurrentIndex()].type === 'SingleChoice')}">
                          <input type="checkbox" ng-if="survey.surveyQuestions[survey.getCurrentIndex()].type !== 'SingleChoice'"> {{answer}}
                        </button>
                      </p>
                    </div>

                    <div class="col-sm-2 survey-right-arrow " ng-click="survey.nextQuestion();" id="nextQuestionBtn">
                      <p>&#8250;</p>
                    </div>
              </div>
            </div>

            <div class="text-center">
              <strong> <p>Question: {{survey.surveyQuestions[survey.scope.index].questionNum}} of {{survey.surveyQuestions.length}}</p> </strong> 
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
           <!-- <nav aria-label="Survey navigation">
              <ul class="pagination pagination-sm justify-content-center">
                <div ng-repeat="question in survey.surveyQuestions" >
                  <li class="page-item">
                    <a class="page-link" id = "navBtn_$index" ng-click="survey.index = $index">{{question.id}}</a>
                  </li>
                </div>
              </ul>
            </nav> -->
          </div>

        </div>

Я бы хотел, чтобы контроллер изменил переменную и соответственно обновил представление

Спасибо за ваше время и заранее спасибо.

1 Ответ

0 голосов
/ 14 января 2019

В вашем HTML это «survey.scope.index», а не «survey.index». Я думаю, что вам может быть неясно разница между использованием «this» и «$ scope». Вы смешиваете два вместе, что не обязательно. Я бы предложил удалить «область действия» и просто указать в своем HTML-коде как «survey.index».

...