ng-model是AngularJS的原生指令,經過require: 'ngModel'能夠更加深刻地處理數據的雙向數據綁定。javascript
ng-model裏面的屬性有:
html
$parsers:保存了從viewValue到modelValue綁定過程當中的處理函數。java
$formatters:保存了從modelValue到viewValue綁定過程當中的處理函數。app
$setViewValue:當AngularJS外部發生某件事情的時候,須要調用這個函數才能讓AngularJS知道應該更新modelValue了。ide
$render:設定當model發生變化時該如何去更新view。函數
$setValidity:設置驗證結果。ui
$viewValue:視圖裏的值。spa
$modelValue:模型裏的值。rest
$parsers、$formatters和$setValidity的例子:orm
<!DOCTYPE html> <html ng-app="myModule"> <head> <meta charset="utf-8"> </head> <body> <article ng-controller="myController"> <form name="myForm"> <input type="text" name="evenInput" ng-model="data.even" even> <input type="text" ng-model="data.even" even> <section ng-show="myForm.evenInput.$error.even"> 只能爲偶數 </section> </form> </article> <script src="../JS/angular.min.js"></script> <script type="text/javascript"> angular.module('myModule', []) .controller('myController', function() { }) .directive('even', function() { return { require: 'ngModel', link: function($scope, iElm, iAttrs, ngModelController) { ngModelController.$parsers.push(function(viewValue) { //parser-語法分析器 if (viewValue % 2 === 0) { ngModelController.$setValidity('even', true); //.$error.even爲false } else { ngModelController.$setValidity('even', false); //.$error.even爲true } return viewValue; }); ngModelController.$formatters.push(function(modelValue) { if (modelValue !== undefined) { modelValue = modelValue + ' some words'; } return modelValue; }); } }; }); </script> </body> </html>
$setViewValue、$render和$viewValue的例子:
<!DOCTYPE html> <html ng-app="myModule"> <head> <meta charset="utf-8"> </head> <body> <article ng-controller="myController"> <my-content ng-model="someText"></my-content> <my-content ng-model="someText"></my-content> </article> <script src="../JS/angular.min.js"></script> <script type="text/javascript"> angular.module('myModule', []) .controller('myController', function() { }) .directive('myContent', function() { return { restrict: 'E', template: '<div contenteditable="true"></div>', require: 'ngModel', replace: true, link: function($scope, iElm, iAttrs, ngModelController) { iElm.on('keyup', function() { $scope.$apply(function() { ngModelController.$setViewValue(iElm.html()); }); }); ngModelController.$render = function() { iElm.html(ngModelController.$viewValue); } } }; }); </script> </body> </html>