K-Dawg
K-Dawg

Reputation: 3299

Adding a function to the scope of an Angular custom directive

I have the following angular directive.

// The component panel
app.directive('component', function () {       
return {
    restrict: 'AE',

    scope: {

        heading: '@heading',
        componentType: '@componentType'


        getComponentUrl: function() {

        var componentPath = "./shell/partials/components/" + componentType + ".html";
        return componentPath;

    }
},


    template: '\
    <div id="panel" class="panel panel-primary panel-component fill scrollable">\
        <div class="panel-heading">\
            <div class="row">\
                <div class="col-sm-6">\
                    <h2 class="panel-title">{{heading}}</h2>\
                </div>\
                <div class="col-sm-6">\
                    <button type="button" class="btn btn-default pull-right btn-expand" data-toggle="tooltip" data-placement="left" title="Go fullscreen" ng-click="">\
                    <i class="fa fa-expand"></i></button>\
                </div>\
            </div>\
        </div>\

        <div class="panel-body fill">\

            <!-- include is used here as different component types may have different attributes\
            so includes are placed here and the directives used within the includes.\
            -->\

            <div ng-include="getComponentUrl()"> </div>\

        </div>\
    </div>\
    ',

    link: function(scope, elm, attrs) {

     }
}
});

As you can see I use the following in the directive's scope:

getComponentUrl: function() { ... }

This doesn't seem to work.

I am trying to supply my ng-include with a predefined string. I appreciate that there are other ways to do this but I wondered i Angular have a means of putting methods into the scope of a directive?

Many Thanks, Kiran

Upvotes: 0

Views: 835

Answers (2)

Calden
Calden

Reputation: 76

You have to move getComponentUrl: function() { ... } to the link directive method. Add this method to a $scope attributes. And make reference to this function within the template .

Upvotes: 0

harishr
harishr

Reputation: 18065

try

app.directive('component', function () {       
return {
    restrict: 'AE',
    link : function(scope){
       scope.getComponentUrl = function() {

        var componentPath = "./shell/partials/components/" + componentType + ".html";
        return componentPath;

    }
    },
    scope: {

        heading: '@heading',
        componentType: '@componentType'



},

Upvotes: 1

Related Questions