2012-12-14 41 views
1

我希望做我自己的网页元素 - 比如,这是一个简单的图形元素:如何在angularjs中扩展默认指令?

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指令相同?

回答

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

+0

这就是更好比我原本以为!谢谢! – zcaudate