简体   繁体   中英

How to include a filter in a custom directive

I'm new to Angular JS and am having trouble with custom directives. I've tried to copy a tutorial and I can't get it working using my own code. Here's the relevant part of my 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>

To start with, I'm just trying to turn the last paragraph into a custom directive. Here's my attempt:

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;
})

This isn't giving the HTML template I expect when I insert it as follows:

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

My first question is why is this not working?

I am also confused as to how to include the currency filter in the linkFunction . What is the syntax for encoding this in Javascript rather than Angular-powered HTML?

Thanks

Answer to your first question, the directive should be declared in camel case. So, declare the directive like this :

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

And call it the way you are doing currently.

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

This should take you inside the directive code.

For your second question, you should use a directive controller. Just create a controller for this directive, inject $filter in that controller and call function of that controller from link function of your directive. Refer this : AngularJs - Use custom filter inside directive controller

app.directive('interestAmount',function($filter){ // camel case, as @isha aggarwal noted
    $filter('filterName')('argument');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM