jgravois
jgravois

Reputation: 2579

AngularJS: How do you use the currency filter inside a directive?

In this plunker, I am trying to apply the currency filter to the display that is not being edited. It is an edit in place directive that displays an input when it is active but I want the filter applied when it is not active.

script:

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


});

view:

<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>

Upvotes: 0

Views: 820

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

You use the filter the same way you would use it in any other template:

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

Here's your modified plunkr.

Upvotes: 2

Related Questions