【问题标题】:How to include a filter in a custom directive如何在自定义指令中包含过滤器
【发布时间】:2015-08-29 17:17:28
【问题描述】:

我是 Angular JS 的新手,在使用自定义指令时遇到了麻烦。我试图复制一个教程,但我无法使用我自己的代码让它工作。 这是我的 HTML 的相关部分:

<div ng-controller="calcController" class="container">
<div class="form-group">
<label for="balInput">Balance:</label>
<input id="balInput" type="text" class="form-control" ng-model="balance" ng-change="updateAnnualInt(balance)" placeholder="Please enter your balance here...">
</div> 
<p>{{'At a '+(interestRate)+'% interest rate you would save...'}}</p>
<p style="text-indent: 30px;" ng-repeat="interest in interests">{{'per '+interest.time+': '}}{{(interest.factor*annualInterest*0.01) | currency:'£'}}</p>

首先,我只是想将最后一段转换为自定义指令。这是我的尝试:

app.directive('interest-amount',function(){
var directive={};
directive.restrict='E';
directive.template="<p style='text-indent: 30px;'>'per '+{{interest.time}}+': '{{(interest.factor*annualInterest*0.01) | currency:'£'}}</p>";

directive.compile=function(element,attributes){
    var linkFunction=function($scope, element,attributes){
        element.html("<p style='text-indent: 30px;'>per "+$scope.interest.time+": "+($scope.interest.factor*$scope.annualInterest*0.01)+"</p>");    
    }
    return linkFunction;
}
return directive;
})

当我按如下方式插入它时,这并没有给出我期望的 HTML 模板:

<interest-amount ng-repeat="interest in interests"></interest-amount>

我的第一个问题是为什么这不起作用?

我也对如何在linkFunction 中包含货币过滤器感到困惑。在 Javascript 而不是 Angular 驱动的 HTML 中编码的语法是什么?

谢谢

【问题讨论】:

  • 是否必须在链接功能中完成?您可以更轻松地在控制器中执行大量操作。

标签: javascript angularjs angularjs-directive


【解决方案1】:
app.directive('interestAmount',function($filter){ // camel case, as @isha aggarwal noted
    $filter('filterName')('argument');
});

【讨论】:

    【解决方案2】:

    回答您的第一个问题,该指令应以驼峰形式声明。所以,像这样声明指令:

    app.directive('interestAmount',function(){
    

    按照你目前的方式来称呼它。

    <interest-amount ng-repeat="interest in interests"></interest-amount>
    

    这应该带你进入指令代码。

    对于第二个问题,您应该使用指令控制器。只需为此指令创建一个控制器,在该控制器中注入 $filter 并从指令的链接函数调用该控制器的函数。 参考这个:AngularJs - Use custom filter inside directive controller

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 2018-02-17
      • 2020-07-18
      • 2016-10-14
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多