methuselah methuselah - 6 months ago 9
AngularJS Question

Use the date filter on a variable pulled from function within view

I'd like to use the date filter on a variable pulled from a function in my view. However, I keep getting the following error message:

Error: [$parse:syntax] Syntax Error: Token '|' is unexpected, expecting [)] at column 201 of the expression [nextStep(3);
sendMessage('xxx', 'xxx',
'Thanks. Your appointment with ' + selectedBusiness.name + ' has been booked for ' + convertDate(booking.date) | date:'fullDate' + ' at ' + booking.time ) + '.'] starting at [| date:'fullDate' + ' at ' + booking.time ) + '.'].


What is the alternative? This is my code so far.

<a ng-click="sendMessage('xxx', 'xxx',
'Thanks. Your appointment with ' + selectedBusiness.name +
' has been booked for ' + convertDate(booking.date) | date:'fullDate' +
' at ' + booking.time ) + '.'">Pay</a>

Answer

That looks like a fair amount of logic in the template. Couldn't you move that off to a controller?

angular.module('myApp', [])

.controller('MainController', ['$scope', 'dateFilter', 'MessageService',
  function($scope, dateFilter, MessageService) {
    // Don't know where these come from so just mocking out
    $scope.selectedBusiness = {
      name: 'ACME'
    };
    $scope.booking = {
      date: '12/31/2016',
      time: '12:00:00PM'
    };

    // handle logic of assembling message here in the controller.
    // can also be unit tested
    $scope.handlePay = function handlePay(selectedBusiness, booking) {
      var convertedDate = dateFilter(new Date(booking.date), 'fullDate');
      var msgText = 'Thanks. Your appointment with ' + selectedBusiness.name +
        ' has been booked for ' + convertedDate +
        ' at ' + booking.time + '.';

      // hand off to MessageService sendMessage (note: this method could just as easily be on the controller, but sending a message
      // seems like it would be shared functionality
      MessageService.sendMessage('xxx', 'xxx', msgText);
    }
  }
])

.service('MessageService', [
  function MessageService() {
    this.sendMessage = function sendMessage(param1, param2, msgText) {
      // use logic to send message
      alert(msgText);
    }
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController">
  <a href="#" ng-click="handlePay(selectedBusiness, booking)">Pay</a>
</div>