【问题标题】:Angular 1 component vs directive definitionAngular 1 组件与指令定义
【发布时间】:2016-10-03 07:42:05
【问题描述】:

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

谢谢,

大卫。

【问题讨论】:

    标签: angularjs node.js angular-components


    【解决方案1】:

    你根本不需要 require:

    .directive('yepNope', YepNopeDirective);
    

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

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

    您使用.componentdirectives stay directives 将您的应用程序转换为组件架构

    【讨论】:

    • 忘记这个简单的例子。这些指令是我们的项目与 Angular 2 不兼容(我们使用编译和替换等)。在那个位置,我们将指令转换为组件是值得的。无论如何,我的问题是为什么我需要做一个新的(当使用一个组件时需要我不需要的指令。
    【解决方案2】:

    我回答我自己的问题。

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 2018-06-14
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 2021-09-03
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多