加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 09:00:36 所属栏目:安全 来源:网络整理
导读:ng-model的作用主要是双向绑定,纯粹输出的话用{{}}方法就可以了。所以ng-model一般是用在有输入功能的元素上,也就是表单和contentEditable的元素上。 要在contentEditable元素上使用需要增加一个directive。 .directive( 'contenteditable' ,[ '$window' ,

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读