Eugene
Eugene

Reputation: 4389

Passing Date/moment object via attribute in AngularJS

I have a directive and I'm trying to pass Date/moment object via attribute. I'm passing it like this: (I know, that I can create isolated-scope and bind it, it is not the case)

<form name="form">
  <input name="field" ng-model="fieldModel" form-field-directive field-date="{{fieldDateModel}}" />
</form>

Without curly brackets the result is obvious, but with I'm getting such quoted string "2015-07-03T10:35:13.691Z".

Is there anyway to work with it?

UPDATE:

angular.module('app', [])
  .controller('AppCtrl', function($scope) {
    $scope.fieldDateModel = moment(); // new Date()
  });

angular.module('app')
  .directive('formFieldDirective', function() {
    return {
      restrict: 'A',
      require: '^ngModel',
      link: function(scope, iElement, iAttrs, ngModelCtrl) {
        ngModelCtrl.$validators.fieldDate = function() {
          if (angular.isUndefined(iAttrs.fieldDate)) {
            return true;
          }

          console.log(iAttrs.fieldDate);
        };
      }
    };
  });

Upvotes: 1

Views: 902

Answers (1)

deostroll
deostroll

Reputation: 11995

You can actually pull the value from the parent scope using $parse which is more reliable.

angular.module('app')
  .directive('formFieldDirective', function($parse) {
    return {
      restrict: 'A',
      require: '^ngModel',
      link: function(scope, iElement, iAttrs, ngModelCtrl) {
        ngModelCtrl.$validators.fieldDate = function() {
          if (angular.isUndefined(iAttrs.fieldDate)) {
            return true;
          }

          console.log(($parse(iAttrs.fieldDate)(scope)).format());
        };
      }
    };
  });

http://jsbin.com/qoheraloge/1/edit?js,console,output

Upvotes: 1

Related Questions