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

前端之家收集整理的这篇文章主要介绍了ng-model的作用及一般元素实现双向绑定前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

  1. .directive('contenteditable',[ '$window',function() {
  2. return {
  3. restrict : 'A',require : '?ngModel',// 此指令所代替的函数
  4. link : function(scope,element,attrs,ngModel) {
  5. if (!ngModel) {
  6. return;
  7. } // do nothing if no ng-model
  8. // Specify how UI should be updated
  9. ngModel.$render = function() {
  10. element.html(ngModel.$viewValue || '');
  11. };
  12. // Listen for change events to enable binding
  13. element.on('blur keyup change',function() {
  14. scope.$apply(readViewText);
  15. });
  16. // No need to initialize,AngularJS will initialize the
  17. // text based on ng-model attribute
  18. // Write data to the model
  19. function readViewText() {
  20. var html = element.html();
  21. // When we clear the content editable the browser
  22. // leaves a <br> behind
  23. // If strip-br attribute is provided then we strip
  24. // this out
  25. if (attrs.stripBr && html === '<br>') {
  26. html = '';
  27. }
  28. ngModel.$setViewValue(html);
  29. }
  30. }
  31. }
  32. } ]);

猜你在找的Angularjs相关文章