微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
                        }
                    }
                }
            } ]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐