将函数添加到 Angular 自定义指令的范围

Adding a function to the scope of an Angular custom directive

我有以下 angular 指令。

// 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) {

     }
}
});

如您所见,我在指令范围内使用了以下内容:

getComponentUrl: function() { ... }

这似乎不起作用。

我正在尝试为我的 ng-include 提供一个预定义的字符串。我很欣赏还有其他方法可以做到这一点,但我想知道我 Angular 有办法将方法放入指令的范围内吗?

非常感谢, 基兰

尝试

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'



},

您必须将 getComponentUrl: function() { ... } 移动到 link 指令方法。将此方法添加到 $scope 属性。 并在模板中引用此函数。