1

我正在尝试编写一个将<time datetime="2012-10-11T12:00:00Z"></time>变成<time datetime="2012-10-11T12:00:00Z">Thu Oct 11 2012</time>.

到目前为止,我的尝试看起来像这样 - myApp 已经定义:(也在JSFiddle上)

angular.module('myApp').directive('time', function() {
  return {
    restrict: 'E',
    link: function (scope, el, at) {
      el.text((new Date(at.datetime)).toDateString());
    }
  };
});

但是at.datetime不会立即填充,所以我会被undefined发送出去,Invalid Date这就是我的视图改变的地方。

我确信可以指定一种单向绑定并重新评估更改,但是我很难遵循文档!我该怎么做?

4

3 回答 3

3

除非你使用一些奇怪的 Angular 版本,否则你的代码根本不应该工作,因为第二个参数 ofmodule是必需的:

除非您已经定义myApp(我假设您没有),否则您上面的代码将无法正常工作。定义模块时,需要第二个参数(依赖项列表):

angular.module('myApp', []); // this creates an app (setter)

angular.module('myApp'); // this creates gives you a reference to an already created app (getter)

否则你的代码似乎工作正常:http: //jsfiddle.net/cjWQB/

也就是说,根据你在做什么(或者我可能不知道time标签是什么),创建一个名为 time 的元素指令(而不是属性指令)可能更有意义。

更新:根据您上面的提琴手,当您定义一个模块时,您的ngApp指令需要指向该命名模块。唯一<html ng-app>可行的方法是当您采用更简单的方法并仅使用以下控制器功能时:

HTML

<html ng-app>
    <div ng-controller="TestCtrl">...</div>
</html>

JavaScript

function TestCtrl($scope) {
}

编辑

根据您对问题的更改,由于您现在使用的是元素指令,因此您需要从不同的地方提取日期。正如马克在上面的评论中建议的那样,那个地方是scope.temporal:http: //jsfiddle.net/Ns2Ny/4/

但是在你的指令中直接引用temporal并不能真正使它可重用,所以你会想加倍努力并使用它$watch来间接引用该值并密切关注它:

http://jsfiddle.net/Ns2Ny/5/

angular.module('myApp',[])
.controller('temporalCtrl', function($scope) {
    $scope.temporal = "2012-11-10T12:00:00Z";
})
.directive('time', function() {
    return {
        restrict: 'E',
        link: function (scope, el, at) {
            console.log('scope', scope);
            console.log('at', at);
            scope.$watch(at.datetime, function (newValue) {
                el.text((new Date(newValue)).toDateString());
            });

        }
    };
});

记下我的console.log陈述。了解其中的内容scopeat调试时间非常有帮助。

于 2013-05-13T14:41:09.100 回答
3

请改用过滤器。内置的日期过滤器:ng-filter:date将为您处理这个问题。

小提琴

    <time datetime="temporal">{{temporal|date:'EEE MMM d yyyy'}}</time>

(有关所有格式选项,请参阅上面的 angularjs 文档链接)

于 2013-05-13T18:45:46.530 回答
1

所以我弄清楚了什么at是(我习惯于将其视为attrs)。

在您的小提琴中,由于您将范围属性指定temporal为指令属性值,

<time datetime="temporal">it hasn't rendered</time>

使用$parse在指令中获取该属性值:

.directive('time', function($parse) {
    return {
        restrict: 'E',
        link: function (scope, el, attrs) {
            var model = $parse(attrs.datetime);
            el.text((new Date(model(scope))).toDateString());
        }
    };
});
于 2013-05-13T15:43:13.003 回答