ng-model是AngularJS的原生指令,通过require: 'ngModel'可以更加深入地处理数据的双向数据绑定。
ng-model里面的属性有:
$parsers:保存了从viewValue到modelValue绑定过程中的处理函数。
$formatters:保存了从modelValue到viewValue绑定过程中的处理函数。
$setViewValue:当AngularJS外部发生某件事情的时候,需要调用这个函数才能让AngularJS知道应该更新modelValue了。
$render:设定当model发生变化时该如何去更新view。
$setValidity:设置验证结果。
$viewValue:视图里的值。
$modelValue:模型里的值。
$parsers、$formatters和$setValidity的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
<!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的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!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
>
|
本文转自 iampomelo 51CTO博客,原文链接:http://blog.51cto.com/iampomelo/1672508,如需转载请自行联系原作者