2015-04-01 71 views
0

我有以下的angular指令。将函数添加到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是否有办法将方法置于指令的范围之内?

非常感谢, 基兰

+1

使用链接功能,在那里你收到该范围,然后在那里添加方法 – harishr 2015-04-01 13:27:49

回答

1

尝试

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' 



}, 
+0

啊,现在看起来很明显,但我当时看不到它。谢谢! – 2015-04-01 13:31:45

+0

当然...对不起忘了! – 2015-04-01 14:05:44

0

你必须移动getComponentUrl:函数(){...}到链接指令方法。将此方法添加到$ scope属性。 并在模板内引用此功能。

相关问题