我是learnig angular,我正在尝试使用vanilla angular实现以下行为。
我有以下html页面,可以动态创建文本输入和按钮。
按下按钮我要验证所有输入(仅检查它们是否为空)并在无效输入下显示消息。 使用jQuery或者使用普通的JS实现起来非常容易,但我正在努力实现角度。
jsFiddle - https://jsfiddle.net/AlexLavriv/zkdodm4b/1/
(function(angular) {
'use strict';
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.instances = [1,2,3,4,5,6,7,8,9,10];
$scope.clicked = function()
{
alert("clicked");
};
}]);
})(window.angular);
<body ng-app="scopeExample">
<div ng-controller="MyController">
<div ng-repeat="instance in instances">
<form name="instance{{$index}}">
<input type="text" required="true" ng-model="txt" name="txt">
<div ng-show="instance{{$index}}.txt.$invalid && instance{{$index}}.txt.$touched"> the input is illegal</div>
</form>
</div>
<input type="button" value="Press" ng-click="clicked()">
</div>
</body>
答案 0 :(得分:1)
这应该会给你你想要的东西(只是一些调整):
(function(angular) {
'use strict';
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.instances = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
$scope.clicked = function() {
angular.forEach($scope.instances, function(instance) {
$scope.outerForm[instance].txt.$setTouched();
});
};
}]);
})(window.angular);
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<body ng-app="scopeExample">
<div ng-controller="MyController">
<form name="outerForm">
<div ng-repeat="instance in instances">
<ng-form name="{{instance}}">
<input type="text" required="true" ng-model="txt" name="txt">
<div ng-show="{{instance}}.txt.$error.required && {{instance}}.txt.$touched"> the input is illegal</div>
</ng-form>
</div>
<input type="button" value="Press" ng-click="clicked()">
</form>
</div>
</body>
&#13;
如果您有任何其他问题,请与我们联系。
答案 1 :(得分:0)
根据当前代码进行的一些观察:
<input>
。所以,将ng-repeat
放在<form>
下面而不是外面。<input type="submit" value="Press" ng-click="submitted = true">
应位于form
元素下。<input name="txt{{$index}}"..
代替 <form name="instance{{$index}}"...
<强>样本强>
var app = angular.module('scopeExample', []);
app.controller('MyController', ['$scope', function($scope) {
$scope.instances = [1,2,3,4,5];
$scope.clicked = function() {
alert("clicked");
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="scopeExample" ng-controller="MyController">
<form name="myForm" ng-submit="myForm.$valid && clicked()" novalidate>
<div ng-repeat="instance in instances">
<input type="text" required="true" ng-model="txt" name="txt{{$index}}">
<div ng-show="submitted == true && myForm.txt{{$index}}.$error.required"> the input is illegal</div>
</div>
<input type="submit" value="Press" ng-click="submitted = true">
</form>
</div>