javascript - 如何将函数应用于 Controller 内的 angularjs 表达式?

标签 javascript angularjs controller angularjs-scope

简单的问题,我想将我的 Controller 范围内的一个函数应用到一个表达式。

这是我的 Controller 中的 HTML

<p><span ng-if="paginaDetail.pubdate !== '' ">Vanaf {{paginaDetail.pubdate}}</span></p>

这是我的javascript

$scope.formatMysqlTimestampToHumanreadableDateTime = function(sDateTime){
    sDateTime = sDateTime.toString();
    var sHumanreadableDateTime = sDateTime.substring(8, 10) + "/" + sDateTime.substring(5, 7) + "/" + sDateTime.substring(0, 4);
    sHumanreadableDateTime += " " + sDateTime.substring(11, 13) + ":" + sDateTime.substring(14, 16);
    return sHumanreadableDateTime;
};

我想做的是像这样将 formatMysqlTimestampToHumanreadableDateTime 应用于 paginaDetail.pubdate

<p><span ng-if="paginaDetail.pubdate !== '' ">Vanaf {{formatMysqlTimestampToHumanreadableDateTime(paginaDetail.pubdate)}}</span></p>

或者这个

<p><span ng-if="paginaDetail.pubdate !== '' ">Vanaf {{paginaDetail.pubdate|formatMysqlTimestampToHumanreadableDateTime}}</span></p>

但这两种方式都不正确。

第一种方法有效,但在控制台上出现此错误

Error: [$interpolate:interr] http://errors.angularjs.org/1.2.16/$interpolate/interr?p0=Tot%20%7B%7BformatMysqlTimestampToHumanreadableDateTime(paginaDetail.endpubdate)%7D%7D&p1=TypeError%3A%20sDateTime%20is%20undefined t/<@http://mysite.local/js/libs/angular.min.js:6:443 g/r@http://mysite.local/js/libs/angular.min.js:78:354 Yd/this.$gethttp://mysite.local/js/libs/angular.min.js:106:161 Yd/this.$gethttp://mysite.local/js/libs/angular.min.js:109:285 f@http://mysite.local/js/libs/angular.min.js:71:234 F@http://mysite.local/js/libs/angular.min.js:75:408 ve/http://mysite.local/js/libs/angular.min.js:76:457

http://mysite.local/js/libs/angular.min.js Line 89

而第二个根本不起作用。

您有什么建议吗?非常感谢。

最佳答案

如果我可以为基于 Controller 的操作提供替代选项...这对于 filter 来说似乎是一个很好的场景

想法是在将输入放入 html 中时使用过滤器,如 {{myDate|format}}

过滤器定义如下:

myApp.filter('format', function () {
   return function (input) {
      //your date parser here
   };
});

或者你想用它做的任何其他事情。这样您就可以重用它,而不必将函数放在您希望使用它的每个 Controller 中。

这是一个 fiddle你可以扩展,让你继续。

编辑 仔细查看错误我认为您的实际问题是未填充.pubdate(TypeError: sDateTime is not defined ).尝试在函数中放置断点或查看控制台显示的内容。

关于javascript - 如何将函数应用于 Controller 内的 angularjs 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24361148/

相关文章:

javascript - 按钮什么都不做?

ruby-on-rails - rails : Flatten array in parameter

来自 JSON POST 正文的 Grails 2.5.0 Controller 操作方法参数

javascript - 带有后退按钮的 Jquery 移动更改页面不起作用

javascript - Node js 三元运算符为什么比较出错?

javascript - JavaScript 字符串如何是一组 "elements"16 位无符号整数值?

javascript - Protractor 单击嵌套按钮元素

javascript - 根据相邻元素的大小或值隐藏 flexbox 元素

javascript - AngularJS/Firebase : $scope data not rendering in view

symfony - 将 Doctrine Repository 注入(inject) Controller