代码之家  ›  专栏  ›  技术社区  ›  beingalex

在自定义指令中生成HTML,在AngularJS中生成$compile

  •  0
  • beingalex  · 技术社区  · 7 年前

    普朗克: https://plnkr.co/edit/IQpGhinzsHUUqmwbHFmQ?p=preview

    我试图创建一个表单,该表单读取一些JSON并创建相关视图。每组问题都有自己的步骤。我无法访问每个 input 使用AngularJS对其进行验证。

    如何访问 answers 在中创建的模型 forEach

    HTML:

        <form ng-app="MyApp" novalidate >
            <section class="question step " ng-controller="StepController">
    
                <div class="step-contents">
                    {{title}}
    
                    <step-contents content="content" ></step-contents>
                </div>
                <button >Prev</button>
                <button ng-click="nextStep(content)">Next</button>
            </section>
        </form>
    

    我的AngularJS:

    var app = angular.module('MyApp', []);
    
    app.controller('StepController', function($scope) {
    
        $scope.index = 0;
    
        $scope.nextStep = function() {
    
            console.log($scope.answers); // This should be the input data for _THIS_ step only
    
        }
    
        $scope.showStep = function() {
    
            //FOREACH HAPPENS HERE
            // Loops over some JSON to generate the following HTML:
            $scope.title = "Step 1 title";
    
            var html = '<input type="number"  ng-model="answers.amount" />';
            html += '<input type="text"  ng-model="answers.name" />';
            $scope.content = html;
    
            //FOREACH ENDS HERE
    
        }
    
        $scope.showStep();
    
    });
    
    app.directive('stepContents', function ($compile) {
    
        var linker = function(scope, element, attrs){
    
            element.html(scope.content);
            $compile(element.contents())(scope);
        };
    
        return {
            restrict: 'E',
            link: linker,
            scope: {
                content: '=',
            },
        };
    
    });
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Frane Poljak    7 年前

    为表单命名,然后可以使用$scope访问表单元素。formName。inputName,它将引用输入的ngModelController。查看Angular的ngFormController和ngModelController文档以了解更多详细信息。