erichardson30
erichardson30

Reputation: 5044

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. 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. This is the first time I have used "component" driven angular and struggling to convert the 'region' directive to a component. I have successfully converted the 'svgMap' directive to a component, just having issues with the 'region' directive.

Upvotes: 1

Views: 583

Answers (1)

BALA
BALA

Reputation: 188

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)
  2. .it should have both view & logic(HTML template & Controller).

As your "region" directive having some DOM manipulation.it violating the basic quality of components.So it can't be converted

Upvotes: 3

Related Questions