简体   繁体   中英

apply ng-show and ng-hide on condition based for dynimcally created elements angular js ng-repeat

apply required filed for some filed in my form but my form is created using the custom directive, So Html is created Dynamically. I am using ng-repeat, i need to show some fields are required when user enter the submit button, but it is showing all fields is required.

 <div ng-repeat="item in items">
        <input type=[item.name]>
 </div>


<p ng-show="ErrorMsg">Error Message </p>

when i am checking the controller logic

Controller.js

$scope.ErrorMsg = false;

if(item.value == null){
   $scope.ErrorMsg = true;

}

But it is showing all fields for error msg. Please suggest me how to approach

Thanks in Advance!

I create a simple plunkr about angularjs dynamic form validation, please refer here: http://plnkr.co/edit/7OJHKsJPoHNqeeStBtnh .

 // Code goes here var myApp = angular.module('myApp',[]); myApp.controller('DemoController', ['$scope', function($scope) { function setTouched(form) { angular.forEach(form, function (value, key) { if (!/^\\$/.test(key)) { form[key].$setTouched(); } }); } var config = []; for (var i = 0; i < 10; i++) { var item = {}; item.name = 'input' + i; item.required = (i%2 === 0) ? true : false; config[i] = item; } $scope.config = config; $scope.save = function() { if ($scope.testForm.$invalid) { setTouched($scope.testForm); } } }]); 
 <!DOCTYPE html> <html ng-app="myApp"> <head> <script data-require="angularjs@1.3.6" data-semver="1.3.6" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.6/angular.min.js"></script> <script data-require="ng-messages@*" data-semver="1.3.16" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-messages.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-controller="DemoController"> <form name="testForm" ng-submit="save()" novalidate> <div ng-repeat="item in config"> <input type="text" name="{{item.name}}" ng-model="item.value" ng-required="item.required" /> <div ng-messages="testForm[item.name].$error" ng-if="testForm[item.name].$invalid && testForm[item.name].$touched"> <div ng-message="required">this is required</div> </div> </div> <button type="submit">save</button> </form> </body> </html> 

Hope this can help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM