如何使用表单。$ addControl()

时间:2014-03-03 20:27:04

标签: javascript angularjs

我正在使用Angular 1.0.8。你如何正确添加编译的表单元素?我假设它与如何使用$ addControl有关?

考虑这个例子:http://jsfiddle.net/lesouthern/LB4Tx/

在此示例中添加select后,只有在输入“myInput”时表单才会生效,它不会识别带有附加选择的“required”指令。

<div ng-app="pageModule"
    ng-controller="parentCtrl">
    <script type="text/ng-template" id="myTemplate">
        <select name="mySelect"
            add-to-form
            ng-model="val"
            required
            ng-options="o.id as o.name for o in options">
            <option value="">Select my option...</option>
        </select>
    </script>
    <form name="myForm"
        id="myForm"
        novalidate
        ng-submit="mySubmit()">
        <input name="myInput"
            ng-model="myInput"
            required />
        <div id="dest"></div>
        <button type="submit">Click me to submit</button>
        {{myForm.$invalid}}
    </form>
    <button ng-click="mkSelect()">create select</button>
</div>



var pageModule = angular.module('pageModule',[])
.controller('parentCtrl',function($scope,$compile) {
    $scope.options = [
        { id : "nissan", name: "Nissan" },
        { id : "toyota", name: "Toyota" },
        { id : "fiat"  , name: "Fiat" },
        { id : "chevy", name: "Chevy" },
        { id : "honda", name: "Honda" },
        { id : "gmc"  , name: "GMC" }
    ];
    $scope.mkSelect = function() {
        var dest = angular.element(document.getElementById('dest')),
            html = angular.element(document.getElementById('myTemplate')).html().trim();
        dest.append($compile(html)($scope));
    }
    $scope.mySubmit = function() {
        console.log('this is my submit');
    }
})
.directive('addToForm',function() {
    return {
        require : ['ngModel'],
        controller : function() {},
        link : function($scope,$element,$attr,$ctrls) {
            var modelCtrl = $ctrls[0];
            $scope.myForm.$addControl(modelCtrl);
        }
    }
});

2 个答案:

答案 0 :(得分:2)

表单。$ addControl()是不必要的。我更正了我的编译命令,现在附加的元素正在向表单控制器注册:http://jsfiddle.net/lesouthern/8CDNc/

$scope.mkSelect = function() {
        var dest = angular.element(document.getElementById('dest')),
            html = angular.element(document.getElementById('myTemplate')).html().trim();
        $compile(html)($scope,function(_element,_scope) {
            dest.append(_element);
        });
    }

答案 1 :(得分:0)

如果您不需要$compile html,可以使用ng-show指令隐藏<select>直到需要。请注意它仍然是required JSFiddle with no $compile

<form>
  ...
  <select name="mySelect" id="multipleSelect" ng-show="mkSelected"
           ng-model="data.singleSelect" required>
  <button type="submit">Click me to submit</button>
</form>
<button ng-click="mkSelected=true">Create Select</button>