Reputation: 501
I am trying to add a few custom angular directives to be called on several views. that said, below is how I have the code setup
app.js
angular
.module('app', [
'app.routes',
'app.config',
'app.users',
'app.plans'
]);
usersCtrl.js
angular
.module('app.users.controllers')
.controller('usersCtrl', usersCtrl)
usersCtrl.$inject = ['$scope', '$http', '$window'];
function usersCtrl($scope, $http, $window) {
/*controller code here*/
}
plansCtrl.js
angular
.module('app.plans.controllers')
.controller('plansCtrl', plansCtrl)
plansCtrl.$inject = ['$scope', '$http', '$window'];
function plansCtrl($scope, $http, $window) {
/*controller code here*/
}
now if I add directive to say users like below
usersCtrl.js with a directive attached
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*/
}
with the above setting if I call directive on users view it works as it should but then if I call it within plan view it also works. that being said, what's the best way to structure directives), where to place custom directive and access those where needed.
Upvotes: 1
Views: 65
Reputation: 2767
I think you are not using directives correctly.
At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
In the above code, your directive has nothing to do with the DOM elements. It just sends an alert. Therefore you should create a Service instead of directive to do so.
Upvotes: 0
Reputation: 1652
Since your directive is module independent and can be shared between different module, my suggestion would be to create a commonmodule and declare your directive in that module. Then you can either register that to global app like other module and use it.
angular
.module('app', [
'app.routes',
'app.config',
'app.commonmodule',
'app.plans'
'app.users',
'app.plans'
]);
Upvotes: 1