【问题标题】:How to get current year with coffeescript如何使用咖啡脚本获取当前年份
【发布时间】:2014-04-25 19:03:52
【问题描述】:

我正在使用 Angular/CoffeeScript/Rails,我正在尝试将当前年份的版权放在页脚中。

使用 JavaScript,我曾经做过这样的事情:

<script type="text/javascript">
<!--
    var theDate = new Date();
    $('.mDate').html('&copy; ' + theDate.getFullYear());
-->
</script>
<span class="mDate"></span>

这是我在 CoffeeScript 中尝试过的 - 在 mainController.coffee 中:

  # mCopyRight
  # ------------------------------------------------------------
  $scope.mCopyRight = ->
    $scope.theDate = new Date();
    $scope.mFullYear = '&copy; ' + theDate.getFullYear();

在 application.html.erb 中

  <span class="mDate">{{mFullYear}}</span>

但是什么都没有显示出来。

就像 new Date 不起作用和/或 .getFullYear();要么

我唯一能想到的就是制作一个常规的 js 文件并在 application.js 文件中要求它:

//= require user-defined/mDate

在 vendor/assets/javascripts/user-defined/ 目录中有一个名为 mDate.js 的文件。

提前致谢

【问题讨论】:

  • 您没有使用$scope.theDate,因为您通过theDate 属性将Date 对象存储在$scope 上...

标签: ruby-on-rails angularjs coffeescript


【解决方案1】:

您已将 theDate 指定为 $scope 的属性。要么从那里阅读:

  $scope.mCopyRight = ->
    $scope.theDate = new Date
    $scope.mFullYear = '&copy; ' + $scope.theDate.getFullYear()

或者如果这个函数只需要这个值,不要使用$scope:

  $scope.mCopyRight = ->
    theDate = new Date
    $scope.mFullYear = '&copy; ' + theDate.getFullYear()

【讨论】:

  • 我明白你的意思,但是当我尝试这个时,它仍然没有用任何东西填充 {{mFullYear}}
  • 您在调用 mCopyRight 函数吗?例如:plnkr.co/edit/IlhoDgbmmPHIsWA8cGuT
  • 我在 p 标签上调用它 onload="mCopyRight()" - 您的代码有效。我将 $scope.mCopyRight 放在 mainController.coffee 文件中,就像您在 plnkr 上的示例一样。顺便说一句,©必须放在我的 _footer.html.erb 模板文件中。这是否意味着coffee 不懂html 代码?感谢您的帮助
  • 我从未尝试将 HTML 编码字符放入我的控制器中。我假设你必须以某种方式告诉 angular 它是一个编码字符串。
  • 更新了版权符号的示例:plnkr.co/edit/MYP1kVmQJkOHVYEMLSwb
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多