Angular 1组件vs指令定义

我对node.js非常陌生,我打算将我们的angular 1指令迁移到组件,以便更容易地转换到Angular 2。

所以,我的问题是,我有一些代码处理这样的几个定义:

'use strict'; var angular = require('angular'); angular.module('dashboard') .directive('yepNope', require('./yep-nope.directive')) //.component('comp', require('./myFirstComponent.component')); .component('comp', new (require('./myFirstComponent.component'))); 

yep-nope.directive和MyFirstComponent.component都以相同的方式定义:

 'use strict'; function MyFirstComponent() { function componentController($element){ var vm = this; init(); function init(){ vm.api = { bar : function(){ console.log('bar called'); }, foo : function(){ console.log('foo called'); } }; } this.$onInit = function(){ console.log("$onInit"); }; this.$postLink = function(){ console.log("$postLink"); }; this.$onChanges = function(changesObj){ console.log("$onChanges"); }; } return { bindings: { }, controller: componentController, //controllerAs: '$ctrl', template:'<div><h1>My Component header</h1></div>' } } module.exports = MyFirstComponent; 

 'use strict'; function YepNopeDirective() { return { restrict: 'E', link: function (scope, element, attrs) { scope.$watch(attrs.check, function (val) { var words = val ? 'Yep' : 'Nope'; element.text(words); }); } } } module.exports = YepNopeDirective; 

有没有任何解释为什么定义组件我需要做一个新的(需要…而指令,这是不需要的?

 .directive('yepNope', require('./yep-nope.directive')) //.component('comp', require('./myFirstComponent.component')); .component('comp', new (require('./myFirstComponent.component'))); 

谢谢,

大卫。

你根本不需要:

 .directive('yepNope', YepNopeDirective); 

如果您确实需要,您可能需要查看您的项目架构。

您不要将指令转换为组件。

使用.component将应用程序转换为组件体系结构,但指令保留指令

我回答我自己的问题。

组件是以与传统指令不同的方式定义的。 虽然指令需要一个函数,但组件需要一个选项对象:

 app.directive(name, fn) app.component(name, options)