2013-05-13 54 views
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是我的看法改变。

我敢肯定,有指定单向绑定和重新评估更改,但我很难跟随文档!我应该怎么做?

+0

有这里涉及到一个模型?你可以分享一个笨蛋,小提琴 – Chandermani 2013-05-13 14:27:37

+0

我没有使用模型,因为我只希望视图随数据更改(不是双向绑定)。我试图把它变成小提琴,但我失败了。这是我到目前为止:http://jsfiddle.net/jphastings/Ns2Ny/ – 2013-05-13 14:39:00

+1

@JP你需要'ng-app =“myApp”'在该Fiddle中 - 你的console.log语句永远不会执行,因为它是没有在正在使用的Angular应用程序中定义。 – Langdon 2013-05-13 14:42:11

回答

3

除非你使用的角一些奇怪的版本,你的代码不应该在所有的工作,因为需要的module第二个参数:

除非你已经定义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的元素指令(而不是属性指令)可能更有意义。

更新:基于上述Fiddler,当您定义模块时,您的ngApp指令需要指向该命名模块。唯一的一次<html ng-app>将工作是当你正在做一个更简单的办法,只是使用像控制器功能:

HTML

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

的JavaScript

function TestCtrl($scope) { 
} 

编辑

基于你的问题的变化,因为你现在正在使用一个元素指令,所以你需要取消日期从不同的地方。正如马克在上面的意见建议,那个地方是scope.temporalhttp://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中的内容非常有用。

+0

感谢您的更正 - 我不习惯将我的代码变成小提琴!工作完成后,我意识到为什么我的问题看起来很奇怪 - 我已经更新了上面的文本。 – 2013-05-13 15:14:02

+0

@JP看我的编辑。 – Langdon 2013-05-13 15:43:42

+1

我终于搞清楚at是什么了。我在看到您的更新之前删除了我的评论,但我会将其添加回来,以便人们可以跟随。 – 2013-05-13 15:52:35

1

所以我想出了at是什么(我习惯把它看作attrs)。

在你fiddle,因为你要指定scope属性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()); 
     } 
    }; 
}); 
+1

@兰登的回答(+1)使用$ watch优于$ parse,如果'temporal'的值可能会改变。 – 2013-05-13 15:47:02

3

使用过滤器,而不是。内置的日期过滤器:ng-filter:date将为您处理此问题。

Fiddle

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

(参见上面的文档你所有的格式选项链接angularjs)

+0

非常好的一点!我将坚持另一个答案 - 但仅仅是因为我打算在前面写一些代码。 – 2013-05-14 08:44:42