如果你看一下this plunk,你会看到如果我通过使用某个函数来改变模型,那么表单不会被告知它并且它不会变脏,我怎么能实现这个行为?
$scope.obj = {};
$scope.setName = function() {
$scope.name = "set name !";
}
<form name="form">
<input type="text" ng-model="name" />
</form>
<button type="button" ng-click="setName()">
setName
</button>
<br />
{{form.$dirty}}
答案 0 :(得分:1)
这是设计的。表单变脏是用户使用其控件,而不是代码修改其底层模型。
但是您可以通过使用form指令在作用域中发布的表单控制器来使表单(或表单的字段)变脏。在您的情况下,由于表单名称为form
,并假设您的输入具有名称:
<input type="text" name="name" ng-model="name" />
$scope.form.name.$setDirty()
答案 1 :(得分:0)
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "";
$scope.obj = {};
$scope.setName = function() {
$scope.name = "set name !";
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.5.4/angular.js"></script>
<!-- By setting the version to snapshot (available for all modules), you can test with the latest master version -->
<!--<script src="https://code.angularjs.org/snapshot/angular.js"></script>-->
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="form">
<input type="text" ng-model="name" required />
</form>
<button type="button" ng-click="setName()">
setName
</button>
<br />
{{form.$dirty}}
<br />
{{form.$touched}}
<br>
{{form.$invalid}}
</body>
</html>
答案 2 :(得分:0)