mark5
mark5

Reputation: 563

Angularjs creating standalone custom directives

i'm trying to modularize my features by components & was wondering is there anyway to include the controller path only in its relevant directives?

i trying to have a folder with structure like this:

-app.js
-directives    
--slider
 ---slider.js
 ---slider.html
 ---slider-carousel-controller.js
 ---slider-single-controller.js

app.js

//require components
require('./directives/banner-slider/banner-slider.js');

My custom directive

app.directive('bannerSlider', [function() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "/directives/banner-slider/banner-slider.html",
    };
}])

How can i achieve this?

Upvotes: 0

Views: 115

Answers (2)

IsraGab
IsraGab

Reputation: 5185

Should be possible.

Just name your controller (dont forget to call the file where your controller is in your index.html file or whatever)

app.directive('bannerSlider', [function() {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: "/directives/banner-slider/banner-slider.html",
            controller: 'yourControllerName'

        };
    }])

Upvotes: 0

Garuuk
Garuuk

Reputation: 2254

How many relative paths do you plan on having for one directive? Usually, directives are used as a repeatable component with repeating properties that are either inherited from the directives parent scope or it's isolate scope (if you choose to make one).

In your case, it sounds like you might have a directive with multiple properties and depending on those properties you'll be doing x, y and z with them.

IMO I would use an isolate scope and pass in your properties through the directives attributes as models.

app.directive('bannerSlider', [function() {
    return {
        scope:{
            property1: "=",
            property2: "="
        },
        restrict: 'E',
        replace: true,
        templateUrl: "/directives/banner-slider/banner-slider.html",
    };
}])

This way you're decoupling your dependency on the directives parent scope and using it the way, imo, directives are meant to be used.

And in your html

<banner-slider property1="value" property2="value"></banner-slider>

Where value is any data that's in the current controller's scope it sits in.

Upvotes: 1

Related Questions