gpt4 book ai didi

javascript - 如何扩展 angularjs 中的默认指令?

转载 作者:行者123 更新时间:2023-11-30 07:16:39 26 4
gpt4 key购买 nike

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

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

最佳答案

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>

然后将指令模块注入(inject)到您的应用中

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

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

关于javascript - 如何扩展 angularjs 中的默认指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13871592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com