簡體   English   中英

如何使用form。$ addControl()

[英]how to use form.$addControl()

我正在使用Angular 1.0.8。 如何正確添加已編譯的表單元素? 我認為它與如何使用$ addControl有關?

考慮以下示例: http : //jsfiddle.net/lesouthern/LB4Tx/

在此示例中添加選擇之后,僅當輸入“ myInput”時,表單才有效,它無法識別帶有附加選擇的“必需”指令。

<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);
        }
    }
});

form。$ 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);
        });
    }

如果不需要$compile html,則可以使用ng-show指令隱藏<select>直到需要。 注意,仍然required JSFiddle而不使用$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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM