2016-10-03 40 views
1

我是很新,Node.js的,我打算給我們的角1個指令,以組件遷移,以便讓用戶輕鬆過渡到角2角1個VS組件定義指令

所以,我的問題是,我有一些代碼,像這樣一對夫婦的定義工作:

'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'))); 

兩個沒錯,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; 

的d

'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'))); 

感謝,

大衛。

回答

0

我回答我的問題組件體系結構。

組件以與傳統指令不同的方式定義。雖然指令需要功能,但組件需要一個選項對象:

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

您不必要求在所有:

.directive('yepNope', YepNopeDirective); 

如果你確實需要需要,您可能需要查看您的項目結構。您不會將指令轉換成組件。

您的應用程序轉換爲使用.componentdirectives stay directives

+0

忘掉這個簡單的例子。這些指令是我們的項目不兼容Angular 2(我們使用編譯和替換)。在那個位置上,我們將指令轉換爲組件是值得的。 無論如何,我的問題是爲什麼我需要做一個新的(當使用指令時需要使用組件時,我不需要。 – David