Improve this Doc View Source ngModel.NgModelController
- type in module ng
NgModelController provides API for the ngModel directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing. It purposefully does not contain any logic which deals with DOM rendering or listening to DOM events. Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding to control elements. Angular provides this DOM logic for most input elements. At the end of this page you can find a custom control example that uses ngModelController to bind to contenteditable elements.
Methods
-  $render();Called when the view needs to be updated. It is expected that the user of the ng-model directive will implement this method. The $render()method is invoked in the following situations:- 
$rollbackViewValue()is called. If we are rolling back the view value to the last committed value then$render()is called to update the input control.
- The value referenced by ng-modelis changed programmatically and both the$modelValueand the$viewValueare different from last time.
 Since ng-modeldoes not do a deep watch,$render()is only invoked if the values of$modelValueand$viewValueare actually different from their previous values. If$modelValueor$viewValueare objects (rather than a string or number) then$render()will not be invoked if you only change a property on the objects.
- 
-  $isEmpty(value);This is called when we need to determine if the value of an input is empty. For instance, the required directive does this to work out if the input has data or not. The default $isEmptyfunction checks whether the value isundefined,'',nullorNaN.You can override this for input directives whose concept of being empty is different from the default. The checkboxInputTypedirective does this because in its case a value offalseimplies empty.ParametersParam Type Details value *The value of the input to check for emptiness. ReturnsbooleanTrue if valueis "empty".
-  $setValidity(validationErrorKey, isValid);Change the validity state, and notify the form. This method can be called within $parsers/$formatters or a custom validation implementation. However, in most cases it should be sufficient to use the ngModel.$validatorsandngModel.$asyncValidatorscollections which will call$setValidityautomatically.ParametersParam Type Details validationErrorKey stringName of the validator. The validationErrorKeywill be assigned to either$error[validationErrorKey]or$pending[validationErrorKey](for unfulfilled$asyncValidators), so that it is available for data-binding. ThevalidationErrorKeyshould be in camelCase and will get converted into dash-case for class name. Example:myErrorwill result inng-valid-my-errorandng-invalid-my-errorclass and can be bound to as{{someForm.someControl.$error.myError}}.isValid booleanWhether the current state is valid (true), invalid (false), pending (undefined), or skipped (null). Pending is used for unfulfilled $asyncValidators. Skipped is used by Angular when validators do not run because of parse errors and when$asyncValidatorsdo not run because any of the$validatorsfailed.
-  $setPristine();Sets the control to its pristine state. This method can be called to remove the ng-dirtyclass and set the control to its pristine state (ng-pristineclass). A model is considered to be pristine when the control has not been changed from when first compiled.
-  $setDirty();Sets the control to its dirty state. This method can be called to remove the ng-pristineclass and set the control to its dirty state (ng-dirtyclass). A model is considered to be dirty when the control has been changed from when first compiled.
-  $setUntouched();Sets the control to its untouched state. This method can be called to remove the ng-touchedclass and set the control to its untouched state (ng-untouchedclass). Upon compilation, a model is set as untouched by default, however this function can be used to restore that state if the model has already been touched by the user.
-  $setTouched();Sets the control to its touched state. This method can be called to remove the ng-untouchedclass and set the control to its touched state (ng-touchedclass). A model is considered to be touched when the user has first focused the control element and then shifted focus away from the control (blur event).
-  $rollbackViewValue();Cancel an update and reset the input element's value to prevent an update to the $modelValue, which may be caused by a pending debounced event or because the input is waiting for some future event.If you have an input that uses ng-model-optionsto set up debounced updates or updates that depend on special events such asblur, there can be a period when the$viewValueis out of sync with the ngModel's$modelValue.In this case, you can use $rollbackViewValue()to manually cancel the debounced / future update and reset the input to the last committed view value.It is also possible that you run into difficulties if you try to update the ngModel's $modelValueprogrammatically before these debounced/future events have resolved/occurred, because Angular's dirty checking mechanism is not able to tell whether the model has actually changed or not.The $rollbackViewValue()method should be called before programmatically changing the model of an input which may have such events pending. This is important in order to make sure that the input field will be updated with the new model value and any pending operations are cancelled.
-  $validate();Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unlessngModelOptions.allowInvalidistrue. If the validity changes to valid, it will set the model to the last available valid$modelValue, i.e. either the last parsed value or the last value set from the scope.
-  $commitViewValue();Commit a pending update to the $modelValue.Updates may be pending by a debounced event or because the input is waiting for a some future event defined in ng-model-options. this method is rarely needed asNgModelControllerusually handles calling this in response to input events.
-  $setViewValue(value, trigger);Update the view value. This method should be called when a control wants to change the view value; typically, this is done from within a DOM event handler. For example, the input directive calls it when the value of the input changes and select calls it when an option is selected. When $setViewValueis called, the newvaluewill be staged for committing through the$parsersand$validatorspipelines. If there are no specialngModelOptionsspecified then the staged value sent directly for processing, finally to be applied to$modelValueand then the expression specified in theng-modelattribute. Lastly, all the registered change listeners, in the$viewChangeListenerslist, are called.In case the ngModelOptions directive is used with updateOnand thedefaulttrigger is not listed, all those actions will remain pending until one of theupdateOnevents is triggered on the DOM element. All these actions will be debounced if the ngModelOptions directive is used with a custom debounce for this particular event. Note that a$digestis only triggered once theupdateOnevents are fired, or ifdebounceis specified, once the timer runs out.When used with standard inputs, the view value will always be a string (which is in some cases parsed into another type, such as a Dateobject forinput[date].) However, custom controls might also pass objects to this method. In this case, we should make a copy of the object before passing it to$setViewValue. This is becausengModeldoes not perform a deep watch of objects, it only looks for a change of identity. If you only change the property of the object then ngModel will not realize that the object has changed and will not invoke the$parsersand$validatorspipelines. For this reason, you should not change properties of the copy once it has been passed to$setViewValue. Otherwise you may cause the model value on the scope to change incorrectly.In any case, the value passed to the method should always reflect the current value of the control. For example, if you are calling$setViewValuefor an input element, you should pass the input DOM value. Otherwise, the control and the scope model become out of sync. It's also important to note that$setViewValuedoes not call$renderor change the control's DOM value in any way. If we want to change the control's DOM value programmatically, we should update thengModelscope expression. Its new value will be picked up by the model controller, which will run it through the$formatters,$renderit to update the DOM, and finally call$validateon it.ParametersParam Type Details value *value from the view. trigger stringEvent that triggered the update. 
Properties
-  $viewValue*The actual value from the control's view. For inputelements, this is a String. SeengModel.NgModelControllerfor information about when the $viewValue is set.
-  $modelValue*The value in the model that the control is bound to. 
-  $parsersArray.<Function>Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. The functions are called in array order, each passing its return value through to the next. The last return value is forwarded to the $validatorscollection.Parsers are used to sanitize / convert the $viewValue.Returning undefinedfrom a parser means a parse error occurred. In that case, no$validatorswill run and thengModelwill be set toundefinedunlessngModelOptions.allowInvalidis set totrue. The parse error is stored inngModel.$error.parse.
-  $formattersArray.<Function>Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control. function formatter(value) { if (value) { return value.toUpperCase(); } } ngModel.$formatters.push(formatter);
-  $validatorsObject.<string, function>A collection of validators that are applied whenever the model value changes. The key value within the object refers to the name of the validator while the function refers to the validation operation. The validation operation is provided with the model value as an argument and must return a true or false value depending on the response of that validation. ngModel.$validators.validCharacters = function(modelValue, viewValue) { var value = modelValue || viewValue; return /[0-9]+/.test(value) && /[a-z]+/.test(value) && /[A-Z]+/.test(value) && /\W+/.test(value); };
-  $asyncValidatorsObject.<string, function>A collection of validations that are expected to perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided is expected to return a promise when it is run during the model validation process. Once the promise is delivered then the validation status will be set to true when fulfilled and false when rejected. When the asynchronous validators are triggered, each of the validators will run in parallel and the model value will only be updated once all validators have been fulfilled. As long as an asynchronous validator is unfulfilled, its key will be added to the controllers $pendingproperty. Also, all asynchronous validators will only run once all synchronous validators have passed.Please note that if $http is used then it is important that the server returns a success HTTP response code in order to fulfill the validation and a status level of 4xxin order to reject the validation.ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { var value = modelValue || viewValue; // Lookup user by username return $http.get('/api/users/' + value). then(function resolved() { //username exists, this means validation fails return $q.reject('exists'); }, function rejected() { //username does not exist, therefore this validation passes return true; }); };
-  $viewChangeListenersArray.<Function>Array of functions to execute whenever the view value has changed. It is called with no arguments, and its return value is ignored. This can be used in place of additional $watches against the model value. 
-  $errorObjectAn object hash with all failing validator ids as keys. 
-  $pendingObjectAn object hash with all pending validator ids as keys. 
-  $untouchedbooleanTrue if control has not lost focus yet. 
-  $touchedbooleanTrue if control has lost focus. 
-  $pristinebooleanTrue if user has not interacted with the control yet. 
-  $dirtybooleanTrue if user has already interacted with the control. 
-  $validbooleanTrue if there is no error. 
-  $invalidbooleanTrue if at least one error on the control. 
-  $namestringThe name attribute of the control. 
This example shows how to use NgModelController with a custom control to achieve data-binding. Notice how different directives (contenteditable, ng-model, and required) collaborate together to achieve the desired result.
contenteditable is an HTML5 attribute, which tells the browser to let the element contents be edited in place by the user.
We are using the $sce service here and include the $sanitize module to automatically remove "bad" content like inline event listener (e.g. <span onclick="...">). However, as we are using $sce the model can still decide to provide unsafe content if it marks that content using the $sce service.
    © 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
    https://code.angularjs.org/1.5.11/docs/api/ng/type/ngModel.NgModelController