1

我希望制作自己的网页元素 - 例如,这是一个简单的图形元素:

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

当我在我的页面中声明它时,我必须使用

<html ng-app="myApp">

是否可以将其安装为默认指令,以便我可以仅包含 .js 文件并开始使用 html 元素而无需指定“myApp”名称 - 与所有ng指令相同?

4

1 回答 1

9

AngularJS 的核心特性之一是模块化。您可以在单独的文件中创建指令模块并向其添加指令。

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

将模块定义为directives.js并将您的应用程序定义为app.js

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

然后将指令模块注入您的应用程序

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

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

于 2012-12-14T02:14:01.287 回答