2015-06-17 4 views
0

Я работаю над проектом съемки с использованием углового. Одна из реализаций не является уверенностью в том, как динамически отображать дочерний элемент на основе ввода пользователя. Например, вопрос с множественным выбором может иметь несколько дочерних вопросов с их дочерними вопросами после выбора родительского вопроса. Я использовал директиву для отображения различных типов вопросов в соответствии с их типами вопросов (текст, несколько вариантов, один выбор и т. Д.), Но как добавлять и отображать свои дочерние вопросы с помощью Angular?Динамически добавлять элемент с помощью angularJS

Большое спасибо.

HTML: 
<h3>Recursive Questions</h3> 
<script type="text/ng-template" id="recursiveQuestionTemplate"> 
    <span>{{question.QuestionDescription}}</span>&nbsp; 
    <span>{{question.QuestionType}}</span>&nbsp; 
    <div ng-include="'/TestTemplate/'+question.QuestionType+'.html'"></div> 
    <br /> 
</script> 
<div class="answer" ng-controller="TreeController"> 
    <form> 
     <div ng-repeat="question in recursiveQuestion" ng-include="'recursiveQuestionTemplate'"> 

     </div> 

    </form> 

    <my-custom>Test1</my-custom> 
    <div class="my-custom">Test2</div> 
</div> 



SingleOption HTML template: 
<div ng-repeat="answer in question.Answers"> 
    <label> 
     <input type="radio" id="{{answer.AnswerID}}" name="{{answer.ParentAnswerID}}" 
       childquestionid="{{answer.ChildQuestionID}}" ng-click="renderChildQuestion(answer.ChildQuestionID,$event)" /> 
     {{answer.AnswerDescription}} 
     {{answer.ChildQuestionID}} 
    </label> 

</div> 



JS snippet: 

    app.controller("TreeController", function ($scope, $http) { 
     //Tree controller used to control template render 
     $scope.renderChildQuestion = function (childQuestionID, $event) { 
      parentAnswerId = $event.currentTarget.id; 

      $scope.parentAnswerId = parentAnswerId; 
      $http.get("/Home/GetQuestionById/" + "test").then(onQuerySubQuestionComplete, onError); 
      // return child element info 
     } 

     //$scope.ChildQuestionID = 111; 

     var onQuerySubQuestionComplete = function (response) { 
      console.log(response.data); 
      //test with Jquery to add element 
      $("#" + parentAnswerId).parents().eq(2).append('<input class="C' + parentAnswerId + '" type="textarea" ng-model="response">new element append here</input>'); 


      var ele = angular.element("<span />"); 
      switch ($scope.user.QuestionType) 
      { 
       case 'text': 
        ele.append('<input type="textarea" ng-model="response">test append</input>'); 
      } 
      //use return type to render html template 
      //$compile(ele); 



     } 
     var onError = function (reason) { 
      alert(reason.data); 
      $scope.error = "Could not get the data."; 

     } 

    //... 
    app.directive('myCustom', function() { 
       return { 
        restrict: 'EC', 
        templateUrl: 
         function (elem, attr) { 
          return '/TestTemplate/SingleOption.html'; 
          //return '/TestTemplate/' + question.QuestionType + '.html' 
         } 
       }; 
      }); 
+3

Просьба указать код. Мы не волшебным образом знаем, как структурировано ваше угловое приложение ;-) – LionC

ответ

0

Установить переменную $scope, равную массиву. Массив будет массивом вопросов. Когда вы возвращаете следующий вопрос, он попадает в переменную $scope.yourArray. По мнению у вас есть:

<div ng-repeat="q in yourArray"></div> 

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

Ваш конкретный случай может быть более сложным, но это должно помочь.

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