gpt4 book ai didi

javascript - 如何访问动态创建的 FormController?

转载 作者:行者123 更新时间:2023-11-29 21:01:11 26 4
gpt4 key购买 nike

我有一系列的项目。每个项目将通过使用 ng-repeatng-form 动态关联到一个表单。

<div ng-repeat="person in people" ng-form="person.$form">
...
</div>

然后我就有可能创建新项目。但是当我这样做时,我希望他们的新形式变得变脏

<button type="button" ng-click="addPerson()">ADD NEW ONE...</button>

在 Controller 中:

$scope.addPerson = function() {
var p = {
name: 'Charles',
color: 'green'
};
$scope.people.push(p);

p.$form.$setDirty(); // <----- THIS WON'T WORK
};

正如上面评论中所写,这是行不通的。它会尝试在 创建 FormController 之前执行该指令。

到目前为止,我无法找到任何解决方案,也无法在此处找到完全相关的已回答问题。

Here是这个例子的 Plunker,增加了一些按钮和标签来处理脏状态和原始状态。

最佳答案

创建一个 custom directive初始化表单:

app.directive("initForm", function() {
return {
link: postLink,
require: 'form'
}
function postLink(scope,elem,attrs,form) {
form.$setDirty();
}
})

并在 HTML 中使用它:

<div ng-repeat="person in people" init-form ng-form="person.$form">
...
</div>

The DEMO

angular.module('app', [])

.controller('MainCtrl', function($scope) {

$scope.people = [
{name: 'Alice',
color: 'pink'
},
{name: 'Bob',
color: 'blue'
}
];

$scope.addPerson = function() {
var p = {
name: 'Charles',
color: 'green'
};
$scope.people.push(p);

//p.$form.$setDirty();
};

})

.directive("initForm", function() {
return {
link: postLink,
require: 'form'
}
function postLink(scope,elem,attrs,form) {
form.$setDirty();
}
})
.ng-pristine {
background-color: #E0F8F7;
}

.ng-dirty {
background-color: #F5A9BC;
}

.bigform.ng-pristine {
background-color: #5882FA;
}

.bigform.ng-dirty {
background-color: #FF0040;
}

.bigform {
padding: 20px;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
<div ng-form="mainForm" class="bigform">
<div ng-repeat="person in people"
init-form
ng-form="person.$form">
<p>{{personIndex}}</p>
<input type="text" ng-model="person.name" />
<input type="text" ng-model="person.color" />
<button type="button" ng-click="person.$form.$setPristine()">RE-PRISTINATE</button>
<label>form is <span ng-show="person.$form.$dirty">dirty</span><span ng-show="person.$form.$pristine">pristine</span></label>
<br />
</div>
<br />
<br />
<button type="button" ng-click="mainForm.$setPristine()">RELOAD</button>
</div>
<br />
<br />
<button type="button" ng-click="addPerson()">ADD NEW ONE...</button>
</body>

关于javascript - 如何访问动态创建的 FormController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46430295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com