简体   繁体   English

带有附加的jQuery append元素不适用于角度范围

[英]Jquery append element with append doesn't apply to angular scope

I have a page that can create a question so the student will answer it later. 我有一个可以创建问题的页面,以便学生稍后回答。 The thing is I start with 3 alternatives and it can grow to 5 alternatives 事情是我从3个替代方案开始,并且可以发展为5个替代方案

<textarea ng-model="question.text" rows="4" required></textarea>
<li class = "item1 alternativa">
            <input type="radio" name="question" id="answer1" value="0">
            <input ng-model="question.alternative0" maxlength = "50" autofocus = "autofocus" placeholder = "Digite a alternativa" class = "item1-textbox" />
            <span class = "icon-remove"title = "Remove item"></span>
        </li>
        <li class = "item2 alternativa">
            <input type="radio" name="question" id="answer2" value="1">
            <input ng-model="question.alternative1" maxlength = "50" autofocus = "autofocus" placeholder = "Digite a alternativa" class = "item2-textbox" />
            <span class = "icon-remove"title = "Remove item"></span>
        </li>
        <li class = "item3 alternativa">
            <input type="radio" name="question" id="answer3" value="2">
            <input ng-model="question.alternative2" maxlength = "50" autofocus = "autofocus" placeholder = "Digite a alternativa" class = "item3-textbox" />
            <span class = "icon-remove"title = "Remove item"></span>
        </li>

and then there's a jquery function to add/remove more alternatives: 然后有一个jquery函数来添加/删除更多的替代品:

  $(".add").click(function() {
  $("ul[class*='questions']").append("<li class = \'item" + count + "alternativa\'>" +
               "<input type='radio' name='question' value=\'" + count + "\' id = \'item" + count + "\' />" +
               "<label for = \'item " + count + " \' title = 'Mark Complete'></label>" +
               "<input ng-model=\question.alternative" + count + "\ maxlength = '50' autofocus = 'autofocus' \
                placeholder='Digite a Alternativa' class = \'item" + count + "-textbox\' />" +
               "<span class='icon-remove' title='Remove item'></span>" +
               "</li>");

So when I insert a new alternative i have a new input tag with the same structure as the first 3, however in my controller i can't reach them as they are printed as undefined 因此,当我插入一个新的替代品时,我有一个新的输入标签,其结构与前三个相同,但是在我的控制器中,我无法访问它们,因为它们被打印为undefined

 $scope.question = {
      text: ""

}

  $scope.saveQuestion = function (question) {
    var videoId = $("#selectLesson").val();
    var questionment = question.text;
    console.log(question);
    var options = [question.alternative0,question.alternative1,question.alternative2,question.alternative3,question.alternative4];
    var answer = $("input[type='radio']:checked").val();
    console.log(options);
    console.log(questionment);
    $scope.esconderQuiz = false;
    //ConteudoService.saveQuestion(videoId,questionment,options,answer);
}

What can i do to have all the questions inside my question scope so I can pass it to my service? 我该怎么办才能将所有问题包含在问题范围内,以便将其传递给我的服务?

edit: Having the 5 alternatives hidden is an option, however it doesn't look like a sophisticate resolution and could cause even more pain. 编辑:隐藏5个替代方案是一个选项,但是它看起来并不复杂,可能会造成更大的痛苦。

As I have already commented: 正如我已经评论过:

If you are using angular, there should not be a need to use jQuery. 如果您使用angular,则不需要使用jQuery。 Use ng-repeat and on add.click , add element to list 使用ng-repeat并在add.click添加元素到列表

Following is a simple representation of it. 以下是它的简单表示。 Also I have used ng-show to toggle visibility of questions. 我也使用ng-show来切换问题的可见性。 If you wish to change it, all you need to do is: 如果您想更改它,您需要做的就是:

$scope.questions[index].visible = true or $scope.questions[index].visible = true $scope.questions[index].visible = true$scope.questions[index].visible = true

 function myCtrl($scope) { $scope.questions = []; var count = 0; for (count = 0; count < 10; count++) { $scope.questions.push(new question(count)); } $scope.add = function(){ $scope.questions.push(new question(count++, true)); } function question(index, visible) { this.title = "Question " + index; this.body = "abc def"; this.answer = "answer"; this.visible = visible?visible:index % 2 == 0; } } 
 .btn { padding: 10px; border: 1px solid gray; width: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> <div ng-app> <div ng-controller="myCtrl"> <div class="btn" ng-click="add()">+</div> <div ng-repeat="q in questions"> <div ng-show="q.visible"> <h3>{{q.title}}</h3> <p>{{q.body}}</p> </div> </div> </div> </div> 

You can really simplify this answer by staying away from JQuery and just use angular two-way binding and ng-repeats. 你可以通过远离JQuery来简化这个答案,只使用有角度的双向绑定和ng-repeats。 This is an example I created to show how easily it can be done. 这是我创建的一个示例,显示了可以轻松完成的示例。

http://codepen.io/anon/pen/aNJeJx http://codepen.io/anon/pen/aNJeJx

This allows you to add and remove questions and answers on the fly editing just the Javascript object and keeps all dom changes to the dom itself. 这允许您在动态编辑Javascript对象时添加和删除问题和答案,并将所有dom更改保留在dom本身。

 angular.module('myApp', []) .controller("Ctrl_List", ["$scope", function($scope) { $scope.newQuestion = { "q": "", "a": [""] } $scope.questions = [{ "q": "Question One?", "a": [ "AnsOne", "AnsTwo", "AnsThree" ] }, { "q": "Question Two?", "a": [ "AnsOne", "AnsTwo" ] }, { "q": "Question Three?", "a": [ "AnsOne", "AnsTwo", "AnsThree", "AnsFour" ] }]; $scope.addQuestion = function() { alert("Added") $scope.questions.push($scope.newQuestion); $scope.newQuestion = { "q": "", "a": [""] } } $scope.addNewAnswer = function() { $scope.newQuestion.a.push(""); } } ]) 
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script> <div ng-app="myApp"> <div class="container" ng-controller="Ctrl_List"> <h1>Questions</h1> Add New Question? <form> <input ng-model="newQuestion.q" placeholder="Question"></input> <br> <input type="button" value="Add Answer Field" ng-click="addNewAnswer()" /> <br> <input ng-repeat="ans in newQuestion.a track by $index" placeholder="{{newQuestion.a[$index]}}" ng-model="newQuestion.a[$index]" /> <br> <br> <input type="button" value="Add Question" ng-click="addQuestion()" />{{newQuestion}} </form> <hr> <div ng-repeat="question in questions"> <b>{{question.q}}</b> <br> <div ng-repeat="answer in question.a" ng-click="question.answer=$index"> [ ] {{answer}} </div> </div> <hr> <h1>Answers</h1> <div ng-repeat="question in questions"> {{$index}}) {{question.a[question.answer]}} </div> </div> 

EDIT Added adding a question method 编辑添加了添加问题的方法

This is sort of the direction you want to go with this. 这是你想要的方向。 Create a directive and out everything in there. 创建一个指令,并在那里的一切。 Like this, 像这样,

(function (angular) {
    'use strict';

    var questionDirective = function ($compile) {
        function controller() {

        }

        function link(scope, element, attrs) {
            var listElement = $compile("<li class = \'item" + count + "alternativa\'>" +
                    "<input type='radio' name='question' value=\'" + count + "\' id = \'item" + count + "\' />" +
                    "<label for = \'item " + count + " \' title = 'Mark Complete'></label>" +
                    "<input ng-model=\question.alternative" + count + "\ maxlength = '50' autofocus = 'autofocus' \
                placeholder='Digite a Alternativa' class = \'item" + count + "-textbox\' />" +
                    "<span class='icon-remove' title='Remove item'></span>" +
                    "</li>");

            var $$addButton = element.find('.add'),
                    $$questionList = angular.element("ul[class*='questions']");

            $$addButton.on('click', function() {
                $$questionList.append(listElement);
            })
        }

        return {
            restrict: 'E',
            link: link,
            controller: controller,
            templateUrl: 'questionDirective.html',
            controllerAs: 'ctrl',
            bindToController: true,
            scope: {}
        };
    };

    angular.module('xapp')
            .directive('questionDirective', ['$compile', questionDirective]);
})(angular);

I am not completely sure how your whole html looks like, but you basically want to compile and then append to your template. 我不能完全确定整个html的样子,但是您基本上想编译然后附加到模板中。 This way you have control over your content. 这样,您就可以控制自己的内容。 One other way to do this will be to have an array of object and then iterate there, and manipulate the object. 实现此目的的另一种方法是拥有一个对象数组,然后在其中进行迭代并操纵该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM