【发布时间】: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