简体   繁体   English

将角度指令重构为组件

[英]Refactoring angular directives as components

I am building an angular component and following along with https://medium.com/@tweededbadger/tutorial-dynamic-data-driven-svg-map-with-angularjs-b112fdec421d#.d413i8wiy since it is accomplishing pretty much what I'm trying to do. 我正在构建一个角度组件并跟随https://medium.com/@tweededbadger/tutorial-dynamic-data-driven-svg-map-with-angularjs-b112fdec421d#.d413i8wiy,因为它几乎完成了我的工作我想做。 They have the following directives : 他们有以下指令:

angular.module('SvgMapApp').directive('svgMap', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        templateUrl: 'img/Blank_US_Map.svg',
        link: function (scope, element, attrs) {
            var regions = element[0].querySelectorAll('.state');
            angular.forEach(regions, function (path, key) {
                var regionElement = angular.element(path);
                regionElement.attr("region", "");
                $compile(regionElement)(scope);
            })
        }
    }
}]);

angular.module('SvgMapApp').directive('region', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {
            scope.elementId = element.attr("id");
            scope.regionClick = function () {
                alert(scope.elementId);
            };
            element.attr("ng-click", "regionClick()");
            element.removeAttr("region");
            $compile(element)(scope);
        }
    }
}]);

The application I am building is using angular 1.5.5, es6 and the component model. 我正在构建的应用程序使用角度1.5.5,es6和组件模型。 This is the first time I have used "component" driven angular and struggling to convert the 'region' directive to a component. 这是我第一次使用“组件”驱动角度并努力将'region'指令转换为组件。 I have successfully converted the 'svgMap' directive to a component, just having issues with the 'region' directive. 我已经成功地将'svgMap'指令转换为一个组件,只是遇到了'region'指令的问题。

For answer the question, First I will give the difference b/w Directive & Components. 为了回答这个问题,首先我将给出不同的指令和组件。

Components is not the replacement for directives. 组件不是指令的替代品。 It's a subset of directives means. 它是指令的一个子集。 When the directive has following two things it will become a component 当指令有以下两件事时,它将成为一个组件

  1. It shouldn't have any DOM manipulation(In directive link function usually we will have our DOM manipulation if needed) 它不应该有任何DOM操作(在指令链接函数中,如果需要,我们通常会有DOM操作)
  2. .it should have both view & logic(HTML template & Controller). .it应该同时具有视图和逻辑(HTML模板和控制器)。

As your "region" directive having some DOM manipulation.it violating the basic quality of components.So it can't be converted 由于你的“区域”指令有一些DOM操作。它违反了组件的基本质量。所以它无法转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM