gpt4 book ai didi

javascript - 构建自定义 Angular Directive(指令)

转载 作者:太空宇宙 更新时间:2023-11-04 15:38:58 24 4
gpt4 key购买 nike

我正在尝试添加一些自定义 Angular Directive(指令)以在多个 View 上调用。也就是说,下面是我如何设置代码

app.js

angular
.module('app', [
'app.routes',
'app.config',
'app.users',
'app.plans'
]);

用户Ctrl.js

angular
.module('app.users.controllers')
.controller('usersCtrl', usersCtrl)

usersCtrl.$inject = ['$scope', '$http', '$window'];

function usersCtrl($scope, $http, $window) {
/*controller code here*/
}

计划Ctrl.js

angular
.module('app.plans.controllers')
.controller('plansCtrl', plansCtrl)

plansCtrl.$inject = ['$scope', '$http', '$window'];

function plansCtrl($scope, $http, $window) {
/*controller code here*/
}

现在,如果我添加指令来表示用户如下所示

附加指令的usersCtrl.js

angular
.module('app.users.controllers')
.controller('usersCtrl', usersCtrl)
.directive('myFirstDirective', ['$window', function($window) {
return {
restrict: 'A',
link: function (scope, element, attrs)
{

alert('my first directive')

}
};
}]);

usersCtrl.$inject = ['$scope', '$http', '$window'];

function usersCtrl($scope, $http, $window) {
/*controller code here*/
}

使用上述设置,如果我在用户 View 上调用指令,它会按预期工作,但如果我在计划 View 中调用它,它也会工作。话虽如此,构建指令的最佳方式是什么),在哪里放置自定义指令并在需要时访问这些指令。

最佳答案

由于您的指令是独立于模块的,并且可以在不同模块之间共享,因此我的建议是创建一个公共(public)模块并在该模块中声明您的指令。然后您可以像其他模块一样将其注册到全局应用程序并使用它。

angular
.module('app', [
'app.routes',
'app.config',
'app.commonmodule',
'app.plans'
'app.users',
'app.plans'
]);

关于javascript - 构建自定义 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050488/

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