简体   繁体   English

指令的角度传递日期对象

[英]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. 但日期被解析为ISO字符串,我无法解析回日期对象。

What is the right and simplest way to do it? 正确和最简单的方法是什么?

Here is my code: 这是我的代码:

html: 的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 输出为:attrs.date: “ 2015-11-16T07:05:53.159Z”日期: 无效日期

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. 谢谢。

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 . 当前,您正在从属性中获取值,然后再次将其从字符串转换为date ,这就是日期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 );
    }
  };
});

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. 使用my-dir而不是myDir,因为angular对连字符分隔的名称执行归一化并将其转换为驼峰式。

Also, since you have isolate scope(scope: {}) for your directive, you don't require interpolate expressions inside the directive attributes. 另外,由于您的指令具有隔离范围(scope:{}),因此不需要在指令属性内插入表达式。

Lastly, change scope in directive to: 最后,将指令的范围更改为:

scope: {
    date: '='
}

And use scope.date in your link function. 并在链接函数中使用scope.date。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM