Why do we need to use ng-model
to make sure that validation works. For instance, in this code if I remove ng-model
attribute then validation breaks but it works as long as there is ng-model
attribute no matter what is the value
of attribute is. So what's the significance of ng-model
in this case? Why do I have to use though it's value does not make much difference?
The value of ng-model
makes all the difference. Not the initial value however, which you are correctly asserting seems to be irrelevant. As soon as you type something into that input box Angular magically assigns the value to the variable assigned to ng-model
.
Subsequently, the value of ng-model
is what Angular's validation code is validating! The data has to get from your fingers to the code somehow and that's the ng-model
.
Let's say you have typed into an input box with ng-model
on it: "I am so cool."
<form ng-controller="SuperController">
<input ng-model="somethingAwesome" />
<button ng-click="someAction()">Click me!</button>
</form
Inside your controller you can access that value on the $scope
.
function SuperController ($scope) {
$scope.someAction = function () {
console.log($scope.somethingAwesome)
// "I am so cool."
}
}
If you set the value inside your controller.. your input box will display that value.
function SuperController ($scope) {
$scope.somethingAwesome = 'You are so cool!'
}
Angular's validation functions read the value of the stuff on your $scope
, which contains the values of items in your view that have the directive ng-model
.