除非你使用的角一些奇怪的版本,你的代码不应该在所有的工作,因为需要的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.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
语句。在调试时了解scope
和at
中的内容非常有用。
有这里涉及到一个模型?你可以分享一个笨蛋,小提琴 – Chandermani 2013-05-13 14:27:37
我没有使用模型,因为我只希望视图随数据更改(不是双向绑定)。我试图把它变成小提琴,但我失败了。这是我到目前为止:http://jsfiddle.net/jphastings/Ns2Ny/ – 2013-05-13 14:39:00
@JP你需要'ng-app =“myApp”'在该Fiddle中 - 你的console.log语句永远不会执行,因为它是没有在正在使用的Angular应用程序中定义。 – Langdon 2013-05-13 14:42:11