zcaudate
zcaudate

Reputation: 14258

how to extend the default directives in angularjs?

I wish to make my own web elements - for example, this is a simple graphics element:

var app = angular.module('myApp', []);

app.directive('gx', function(){
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: {w: '@',
            h: '@'},
    template: '<svg class="gx" ng-transclude></svg>',

    controller: function ($scope, $element) {
      var children = $scope.children = [];
      this.addChild = function (c) {
        children.push(c);
      };
    },
    link: function (scope, element, attrs, gxCtrl){
      if (gxCtrl) gxCtrl.addChild(scope);
      scope.$watch('w+h', function(val){
        var w = scope.w||"100%",
            h = scope.h||"100%";
        $(element).attr("height", h).attr("width", w);
      });
    }
  };
});

when I declare it in my page, I have to use

<html ng-app="myApp">

is it possible to install it as a default directive, so that I can just include the .js file and start using html elements without having to specify the 'myApp' name - the same way as all the ng directives?

Upvotes: 1

Views: 959

Answers (1)

jaime
jaime

Reputation: 42031

One of AngularJS core features is modularity. You can create a directives module in a separate file and add directives to it.

angular.module('directives',[])
.directive('gx', function(){
  return {/** directive definition object **/ };
});

Define the module into directives.js and your app into app.js

<script src="directives.js"></script>
<script src="app.js"></script>

Then inject the directives module into your app

var app = angular.module('myApp', ['directives']);

Example: http://plnkr.co/edit/OgNr4Qx3SBbWwcH9NSfu?p=preview

Upvotes: 9

Related Questions