问题描述
最近项目组需要将项目转到从ng1 转到 ng2。看了相关ng2关于指令的文档,可这是一头雾水,知道将$element 对应ng2 ElementRef,在细节还是不知所措,求指教!
Ng1 Directive.directive('Touchmove', function () { return {controller: ['$scope', '$element', function ($scope, $element) { $element.bind('touchstart', onTouchStart); function onTouchStart(event) {event.preventDefault();$element.bind('touchmove', onTouchMove);$element.bind('touchend', onTouchEnd); } function onTouchMove(event) {var method = $element.attr('ng-touchmove');$scope.$event = event;$scope.$apply(method); } function onTouchEnd(event) {event.preventDefault();$element.unbind('touchmove', onTouchMove);$element.unbind('touchend', onTouchEnd); }}] }});.directive('Touchend', function () { return {controller: ['$scope', '$element', function ($scope, $element) { $element.bind('touchend', onTouchEnd); function onTouchEnd(event) {var method = $element.attr('ng-touchend');$scope.$event = event;$scope.$apply(method); }}] }}) HTML
<p touchend='mRelease()' touchmove='mTouch($event)' ng-click='mTouch($event)' ><p ng-repeat='c in indexs' style='width:100%;height:{{hIndex}}px;'> {{c}}</p></p>Ng2 ??
问题解答
回答1:谢邀!Angular 2 中指令分为以下三种:
组件(Component directive):用于构建UI组件,继承于 Directive 类。通过@Component() 装饰器定义
属性指令(Attribute directive): 用于改变组件的外观或行为。通过 @Directive()装饰器定义
结构指令(Structural directive): 用于动态添加或删除DOM元素来改变DOM布局。如ngIf、ngFor。特点是号开头的指令,是语法糖,表示使用HTML 5模板语法<template>
另外可以先看一下 Angular 2 修仙之路 - 目录中两个章节:
Angular 2 vs Angular 1 (以下两篇就是介绍Ng1与Ng2指令区别,中文版还没整理出来,不好意思)
Component Property Binding with @Input() in Angular 2
Component Event Binding with @Output() in Angular 2
Angular 2 组件学习线路 (仅供参考)
这个是比较全的组件学习线路,可以先根据文章说明,大致了解一下。主要的内容是输入属性、输出属性、宿主属性绑定和事件绑定。
回答2:我也是从ng1换到ng2的,两个框架的路子完全不同了,哪怕是你说的ElementRef也并非去获取DOM而是使用render渲染,所以项目不是非常小的话,考虑重构吧
回答3:放弃,将项目从1升级至2!