如何使用dart angular构建一个就地编辑

时间:2017-03-14 11:02:17

标签: angularjs angular-dart

我对直接写入div的angularjs示例印象深刻(无需隐藏/显示)

https://docs.angularjs.org/guide/forms部分实现自定义表单控件(使用ngModel)

    angular.module('form-example2', []).directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$render = function() {
      elm.html(ctrl.$viewValue);
    };
}});

我实际上不明白是谁拦截了keyup事件以将其放入$ viewValue并将其写回div,所以我无法以dart angular重现此功能。

有人可以用指令解释那个div幕后发生了什么吗? AngularDart代码如何看起来像?

2 个答案:

答案 0 :(得分:3)

您可以编写自己的指令并根据需要调整交互和更新调用。 (选择如何处理模糊,键盘,keydown事件等。)这是我如何做到的。这是一个基本的例子,如何使用Angular 2和Dart(AngularDart)进行双向绑定来构建自定义指令。

<强> contenteditable.dart

import 'dart:html';
import 'package:angular2/core.dart';

@Directive(
  selector: '[contentEditable]', //Selector that you'll use in your templates
)
class ContentEditable implements OnChanges {
  Element _el; //holding element's properties and content

  @Input()
  String contentEditableModel;

  @Output()
  EventEmitter contentEditableModelChange = new EventEmitter();

  //Constructor
  ContentEditable(ElementRef ref) {
    _el = ref.nativeElement;
  }

  //This method is called on blur event (can be also 'keyup', 'keydown' etc.)
  @HostListener('blur')
  void onBlur() {
    contentEditableModelChange.emit(_el.text);
  }

  //This implementation updates the editable elements content
  //when model is updated somewhere else
  @override
  ngOnChanges(Map<String, SimpleChange> changes) {
    changes.forEach((String propName, SimpleChange change) {
      _el.innerHtml = change.currentValue;
    });
  }
}

以下是如何在组件中使用指令(您刚刚创建的)...

<强> my_component.dart

import 'package:angular2/core.dart';
import 'package:angular2_components/angular2_components.dart';

import 'contenteditable.dart';

@Component(
  selector: 'my-component',
  styleUrls: const ['app_component.css'],
  templateUrl: 'my_component.html',
  directives: const [ContentEditable],
)

class MyComponent {
  String some_var = "Hello editable!";
}

<强> my_component.html

<div contentEditable [(contentEditableModel)]="some_var">Some text that's overridden by some_var</div>
<h1>Here you see the value updating: {{some_var}}</h1>
And from here you can update it too: <input [(ngModel)]="some_var">

答案 1 :(得分:1)

contenteditable是一个html5属性,允许您编辑任何内容,与角度本身无关:https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

设置和读取值由ngModel指令处理,你可以在AngularDart中使用它 - 我没有尝试过,但我认为它应该可行。如果它不是,你可能需要手动监听以改变事件(甚至更好地将补丁发送到ngModel)。