I am trying to implement the basic angular form validation. I have implemented the same. But I am curious to know, why it does not works if I am not using ng-model.
Link for plunker to show the same behaviour
I am trying to implement the basic angular form validation. I have implemented the same. But I am curious to know, why it does not works if I am not using ng-model.
Link for plunker to show the same behaviour
On
Because without the ng-model, the input elements aren't bound to anything within your application's scope.
On
Angular has own context model. (scope or something else) If you treat form outside Angular world, form can't get any information in Angular point of view.
If you doesn't want to use ng-model, use plain javascript validation method.
On
ng-model="value" defines that the value of that particular element is from angular's context. It checks for the value in the scope where the element is declared. For example, we have onclick="call()" and ng-click="call()" methods. The onclick event search for the function that is outside of angular context, ng-click event search for the function in the scope.
<div ng-app="app" ng-controller="Ctr" onclick="call()" ng-click="call()"></div>
<script>
function call(){
console.log('out of angular');
}
angualr.app('app', function($scope){
$scope.call = function(){console.log('insode angular')}
})
</script>
In the above code if you remove onclick, then ng-click prints 'inside angular', if you remove ng-click, then onclick prints out of angular. If both will be there, both will be called and prints.
In the same way, if you remove ng-model, you will loose the control over the value of input in angular context and $error, $invalid doesn't know what to validate.
ngModeldirective holds an instance ofNgModelControllercontaining the services for data-binding, validation, CSS updates, and value formatting and parsing. IfngModelitself is not there, validation will not work. For form validation to work you need both form instance which can be published to scope usingnameattribute and the form input control (ngModel). The below description from Angular documentation explains that: