从子指令

时间:2015-11-26 08:00:39

标签: javascript angularjs

我在angularjs中创建了一个带有子指令的自定义指令。子指令负责生成动态输入元素,例如文本框,单选按钮和复选框,这些元素都具有从数组填充的某些默认值。我需要检索动态创建的输入元素的值。

      for (i = 0; i < scope.arr.length; i++) {

            if (scope.arr[i].type == "input" && scope.arr[i].value) {
                angular.element(document.getElementById('form-block'))
                    .append($compile("<div>" + "</br>" + scope.arr[i].name + "</br>" + "<input type='text' ng-model='model[\"" + scope.arr[i].name + "\"]'/></div>")(scope));
            } else if (scope.arr[i].type == "password" && scope.arr[i].value) {
                angular.element(document.getElementById('form-block'))
                    .append($compile("<div>" + "</br>" + scope.arr[i].name + "</br>" + "<input type='password' ng-model='model[\"" + scope.arr[i].name + "\"]'/></div>")(scope));

            } else if (scope.arr[i].type == "checkbox" && scope.arr[i].value) {
                angular.element(document.getElementById('form-block'))
                    .append($compile("<div>" + "</br>" + scope.arr[i].name + "</br>" + "<input type='checkbox' ng-model='model[\"" + scope.arr[i].name + "\"]'/></div>")(scope));

            } else if (scope.arr[i].type == "radio" && scope.arr[i].value) {
                angular.element(document.getElementById('form-block'))
                    .append($compile("<div>" + "</br>" + scope.arr[i].name + "</br>" + "<input type='radio' value='" + scope.arr[i].value + "'" + "ng-model='model[\"" + scope.arr[i].name + "\"]'/></div>")(scope));
            }
        }

以下是小提琴与我的代码的链接,

https://jsfiddle.net/f5r7onko/

我尝试了多种组合,但我无法检索这些值。任何想法或建议对我都有很大的帮助。感谢

1 个答案:

答案 0 :(得分:0)

您可以使用模型直接访问该值。这是更新的jsfiddle https://jsfiddle.net/f5r7onko/1/

例如。在HTML中,您可以像这样访问

<p>textbox1 value = {{model.Textbox1}}</p>
<p>textbox2 value = {{model.Textbox2}}</p>
<p>textbox3 value = {{model.samplePassword}}</p>