我有一个选择元素:
<select ng-model="user" data-ng-options="user.Forename + ' ' + user.Surname for user in allusers"></select>
在此之后,我有3个输入:
<input type="text" value="{{ user.Surname }}" />
<input type="text" value="{{ user.Forename }}" />
<input data-convert-json-date data-jsondate="{{ user.DOB }}" />
第三个输入有一个指令,用于将unix样式日期转换为人类可读日期。
myApp.directive('convertJsonDate', function () {
return {
restrict: 'EAC',
link: function (scope, el, attrs) {
var JSONdate = attrs.jsondate;
var formattedDate = new Date(parseInt(JSONdate.substr(6)));
el.val(formattedDate.format("dd/mm/yyyy"));
}
}
});
但是,即使前两个输入在选择更改时更新,第三个输入仍为空白。
为什么这个指令无效?
答案 0 :(得分:3)
因为你没有注意变化,而不是因为输入标签......
您需要更改以下代码:
myApp.directive('convertJsonDate', function () {
return {
restrict: 'EAC',
scope:{
jsondate: '@'
},
link: function (scope, el, attrs) {
scope.$watch('jsondate', function(JSONdate){
var formattedDate = new Date(parseInt(JSONdate.substr(6)));
el.val(formattedDate.format("dd/mm/yyyy"));
})
}
}
});
正如@ryeballar所建议的,而不是孤立的范围和观察,你可以使用attrs.$observe()
,它会更有效率:
attrs.$observe('jsondate', function (JSONdate) {
var formattedDate = new Date(parseInt(JSONdate.substr(6)));
el.val(formattedDate.format("dd/mm/yyyy"));
});
答案 1 :(得分:3)
您可以使用链接功能的.$observe()
参数的attr
方法来获得您想要的内容,无需隔离范围本身并为其创建观察程序。
<强> HTML 强>
<input type="text" value="{{ user.Surname }}" />
<input type="text" value="{{ user.Forename }}" />
<input data-convert-json-date="{{ user.DOB }}" />
<强> JAVASCRIPT 强>
myApp.directive('convertJsonDate', function () {
return function(scope, elem, attr) {
attr.$observe('convertJsonDate', function(JSONdate) {
var formattedDate = new Date(parseInt(JSONdate.substr(6)));
elem.val(formattedDate.format("dd/mm/yyyy"));
});
};
});
答案 2 :(得分:1)
所以我认为你的指令没有被触发,因为属性和你的指令之间没有绑定......
你可以在这做两件事......
1)改为编写过滤器并使用ng-model绑定到您的属性。例如。 Ng-model =&#39; user.DOB | jsondate&#39 ;.请参阅filters。
2)更改您的指令以使用范围隔离并绑定到您的属性。 E.g。
myApp.directive('convertJsonDate', function () {
return {
restrict: 'A',
scope:{
jsondate: '@'
},
link: function (scope, el, attrs) {
scope.$watch('jsondate', function(JSONdate){
var formattedDate = new Date(parseInt(JSONdate.substr(6)));
el.val(formattedDate.format("dd/mm/yyyy"));
})
}
}
});
编辑:@Bogdan Savluk打败了我:)