依赖内置ng-model指令的自定义指令

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的例子:

<!DOCTYPEhtml>
<htmlng-app="myModule">

<head>
<metacharset="utf-8">
</head>

<body>
<articleng-controller="myController">
<formname="myForm">
<inputtype="text"name="evenInput"ng-model="data.even"even>
<inputtype="text"ng-model="data.even"even>
<sectionng-show="myForm.evenInput.$error.even">
只能为偶数
</section>
</form>
</article>
<scriptsrc="../JS/angular.min.js"></script>
<scripttype="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
}
returnviewValue;
});
ngModelController.$formatters.push(function(modelValue){
if(modelValue!==undefined){
modelValue=modelValue+'somewords';
}
returnmodelValue;
});
}
};
});
</script>
</body>

</html>


$setViewValue、$render和$viewValue的例子:

<!DOCTYPEhtml>
<htmlng-app="myModule">

<head>
<metacharset="utf-8">
</head>

<body>
<articleng-controller="myController">
<my-contentng-model="someText"></my-content>
<my-contentng-model="someText"></my-content>
</article>
<scriptsrc="../JS/angular.min.js"></script>
<scripttype="text/javascript">
angular.module('myModule',function(){

})
.directive('myContent',function(){
return{
restrict:'E',template:'<divcontenteditable="true"></div>',require:'ngModel',replace:true,ngModelController){
iElm.on('keyup',function(){
$scope.$apply(function(){
ngModelController.$setViewValue(iElm.html());
});
});
ngModelController.$render=function(){
iElm.html(ngModelController.$viewValue);
}
}
};
});
</script>
</body>

</html>

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...