user2436448
user2436448

Reputation: 565

Angular passing date object to directive

I am trying to pass a date object to directive via attribute. but the date is parsed to ISO string and i have no way to parse it back to date object.

What is the right and simplest way to do it?

Here is my code:

html:

<body ng-app="myApp">
    <div ng-controller="ctrl">
     <div myDir date={{date}}></div>
    </div>
  </body>

controller:

var app = angular.module('myApp', []).controller('ctrl', function($scope) {
  $scope.date = new Date();
});

directive:

app.directive('myDir', function() {
  return {
    template: '',
    scope: {},
    link: function(scope, el, attrs){
      console.log('attrs.date: ', attrs.date;);
      var d = new Date(d);
      console.log('date: ', d);
    }
  };
});

The output is: attrs.date: "2015-11-16T07:05:53.159Z" date: Invalid Date

I don't want to use the way of get the parameter on the scope with '='. Is there other way to send date to directive?

Thanks.

Upvotes: 0

Views: 3731

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Currently you are getting value from attribute and then again you are converting that value from string to date, which is why your date is becoming invalid.

Instead of passing value through attribute, I'd suggest you to pass that value from isolated scope of directive, which will pass the object value without need of any conversion.

Markup

<div my-dir my-date="date"></div>

Directive

app.directive('myDir', function() {
  return {
    template: '',
    scope: {
       myDate : '=' //mapped with `my-date` attribute on directive element.
    },
    link: function(scope, el, attrs){
      console.log('date: ', scope.myDate );
    }
  };
});

Upvotes: 3

Tarun Dugar
Tarun Dugar

Reputation: 8971

Change your template to:

<div my-dir date="date"></div>
</div>

my-dir instead of myDir because angular performs normalisation on hyphen separated name and converts it to camel case.

Also, since you have isolate scope(scope: {}) for your directive, you don't require interpolate expressions inside the directive attributes.

Lastly, change scope in directive to:

scope: {
    date: '='
}

And use scope.date in your link function.

Upvotes: 0

Related Questions