ng-model的作用及一般元素实现双向绑定

ng-model的作用主要是双向绑定,纯粹输出的话用{{}}方法就可以了。所以ng-model一般是用在有输入功能的元素上,也就是表单和contentEditable的元素上。
要在contentEditable元素上使用需要增加一个directive。

.directive('contenteditable',[ '$window',function() {
                return {
                    restrict : 'A',require : '?ngModel',// 此指令所代替的函数
                    link : function(scope,element,attrs,ngModel) {
                        if (!ngModel) {
                            return;
                        } // do nothing if no ng-model
                        // Specify how UI should be updated
                        ngModel.$render = function() {
                            element.html(ngModel.$viewValue || '');
                        };
                        // Listen for change events to enable binding
                        element.on('blur keyup change',function() {
                            scope.$apply(readViewText);
                        });
                        // No need to initialize,AngularJS will initialize the
                        // text based on ng-model attribute
                        // Write data to the model
                        function readViewText() {
                            var html = element.html();
                            // When we clear the content editable the browser
                            // leaves a <br> behind
                            // If strip-br attribute is provided then we strip
                            // this out
                            if (attrs.stripBr && html === '<br>') {
                                html = '';
                            }
                            ngModel.$setViewValue(html);
                        }
                    }
                }
            } ]);

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...