$compile не обновляет динамически сгенерированную HTML-среду выполнения

Вот jsfiddle: https://jsfiddle.net/vikramkute/eq3zpmp9/5/

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

Ожидаемый результат

1 Quest
2 Quest
3 Quest

но я получаю последнее значение повторяется три раза. Согласно моим методам проб и ошибок, я чувствую, что проблема с $compile. Я пробовал разные решения на разных форумах, но ничего не получалось. Любая помощь высоко ценится. Благодарю.

В директиве (в пределах функции ссылки)

            scope.obj =
            [
                {
                    "questionText": "1 Quest"
                },
                {
                    "questionText": "2 Quest"
                },
                {
                    "questionText": "3 Quest"
                }
            ]

            scope.addData = function() {
                for (var i = 0; i < scope.obj.length; i++) {
                    addSlide(scope.obj[i]);
                }
            }

           addSlide = function (obj) {
               scope.singleObj = obj;
               el = $('<div ng-bind="singleObj.questionText"></div>');
               scope.owl.append(el);
               $compile(el)(scope);
           };

Выход:

3 Quest
3 Quest
3 Quest

Вот полная директива:

angular.module('journeycarousel', [])
    .directive('journeyCarousel', function ($compile) {
        return {
            restrict: 'E',
            templateUrl: '../components/journeyCarousel/journeyCarousel.html',
            transclude: true,
            link: function (scope, element) {

                scope.obj =
                    [
                        {
                            "questionText": "1 Quest"
                        },
                        {
                            "questionText": "2 Quest"
                        },
                        {
                            "questionText": "3 Quest"
                        }
                    ]

                scope.addData = function() {
                    for (var i = 0; i < scope.obj.length; i++) {
                        addSlide(scope.obj[i]);
                    }
                }

                addSlide = function (obj) {
                    scope.singleObj = obj;
                    el = $('<div ng-bind="singleObj.questionText"></div>');
                    scope.owl.append(el);
                    $compile(el)(scope);
                };
            }
        }
    });

Выше код является упрощенной версией. Это фактический код:

    scope.singleObj = obj;
    el = $('<div class="questionContainer" <div ng-repeat="obj in singleObj"> ng-click="onSlideClick($event,singleObj)"> <div class="item"> <div class="questionSection" ng-bind="singleObj.questionText"></div> <div class="answerSection" ng-bind="singleObj.questionAnswer + singleObj.questionUnitOfMeasure"></div> </div> </div>');
   $('.owl-carousel').owlCarousel('add', el).owlCarousel('update');
   $compile(el)(scope);

2 ответа

Решение

Я считаю, что причина вашего выхода

3 Quest
3 Quest
3 Quest

потому что в вашем случае цикл дайджеста включается только после цикла for 3 раза. Итак, к концу 3-й итерации

scope.singleObj 

всегда будет

{
     "questionText": "3 Quest"
}

Таким образом, все соблюдаемые элементы всегда будут относиться к одному scope.singleObj

чтобы избавиться от того, что вы можете сделать

$scope.singleObj = [];
var addSlide = function(obj, i) {
    $scope.singleObj.push(obj);
    var ele = '<div ng-bind=\"singleObj[' + i + '].questionText"></div>'
    el = $(ele);
    $("#container").append(el);
    $compile(el)($scope);
};

$scope.addData = function() {
    for (var i = 0; i < $scope.newCarouselSlideData.length; i++) {
        addSlide($scope.newCarouselSlideData[i], i);
    }
}

Используйте структуру ниже, возможно, вы ошибаетесь с объектно-ориентированной концепцией:

addSlide = function (obj) {
        scope.singleObj = angular.copy(obj);
        el = $('<div ng-bind="singleObj.questionText"></div>');
        scope.owl.append(el);
        $compile(el)(scope);
};
Другие вопросы по тегам