2012-12-14 37 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