AngularJS:你如何在指令中使用货币过滤器?

时间:2014-10-31 21:32:12

标签: angularjs angularjs-directive

在此plunker中,我尝试将货币过滤器应用于未编辑的显示。它是一个编辑就位指令,当它处于活动状态时会显示一个输入,但我希望在它不活动时应用该过滤器。

脚本:

var app = angular.module('plunker', []);

app.directive('editInPlace', function () {
  return {
      restrict: 'E',
      scope: {
          value: '='
      },
      template: '<span ng-click="edit()" ng-bind="value" ng-show="!editing"></span><input ng-model="value" ng-blur="onBlur()" ng-show="editing"></input>',
      link: function ($scope, element, attrs) {
          var inputElement = element.find('input');

          // reference the input element
          element.addClass('edit-in-place');

          // Initially, we're not editing.
          $scope.editing = false;

          // ng-click handler to activate edit-in-place
          $scope.edit = function () {
              $scope.editing = true;

              // element not visible until digest complete
              // timeout causes this to run after digest
              setTimeout(function() {
                inputElement[0].focus();
              });
          };

          $scope.onBlur = function() {
              $scope.editing = false;
          };
      }
  };
});

app.controller('MainCtrl', function($scope) {
  $scope.contacts = [
    {name: 'Katniss', total: 35645.58}, 
    {name: 'Peeta', total: 25178.21}
  ];


});

视图:

<body ng-controller="MainCtrl">
    <ul style="margin-top:20px;">
      <li ng-repeat="contact in contacts">
        {{contact.name}} -- 
          <edit-in-place value="contact.total"></edit-in-place>
      </li>
  </ul>
  <hr/>
  <pre>{{contacts}}</pre>
  <hr/>
  </body>

1 个答案:

答案 0 :(得分:2)

您使用过滤器的方式与在任何其他模板中使用过滤器的方式相同:

template: '<span ng-click="edit()" ng-show="!editing">{{ value | currency}}</span><input ng-model="value" ng-blur="onBlur()" ng-show="editing"></input>'

这是你的modified plunkr