gpt4 book ai didi

javascript - Angularjs 指令 - 无法从隔离范围中检索值

转载 作者:行者123 更新时间:2023-12-02 16:13:52 26 4
gpt4 key购买 nike

我有一个自定义指令来格式化日期时间。我在多个 View 中使用它,除了一个实例之外,它似乎可以全面工作。当 request.created 传递给它时(下面的 HTML),第一个 console.log(scope) 指示“日期”已正确设置并传递给指令。但 console.log(scope.date) 打印为空。

我在其他 View 和同一 View 中的几个“email.sendDate”上都工作正常。

请求的值从服务器检索并由 Controller 设置。

myApp.directive('friendlydate', function () {
function link(scope, element, attrs) {
console.log(scope);
console.log(scope.date);
var uglydate = scope.date;
//do stuff
scope.formatteddate = prettydate;
};

return {
restrict: 'E',
scope: {
date: '@'
},
link: link,
template: '{{formatteddate}}'
};
});

在我的 html 中,我有

<div class="col-md-6">
<dl class="dl-horizontal">
<dt>Created</dt>
<dd>
<friendlydate date="{{request.created}}"></friendlydate>
</dd>
<dt>IP Address</dt>
<dd>{{request.ipAddress}}</dd>
<dt>Browser</dt>
<dd>{{request.browser}}</dd>
</dl>
</div>

<table>
<tbody ng-repeat="email in request.emails">
<tr>
<td>
<friendlydate date="{{email.sendDate}}"></friendlydate>
</td>
<td>{{email.subject}}</td>
<td>{{emailStatus(email.status)}}</td>
<td><button class="btn btn-primary">view</button></td>
</tr>
</tbody>
</table>

enter image description here

如果需要更多信息,请告诉我。我快要疯了,请帮忙。

最佳答案

您的数据是从服务器检索并由 Controller 设置的。您的响应可能会有延迟,如果是这种情况,我的解决方案适合您。

在你的 View 中使用 ng-if :

<friendlydate date="{{request.created}}" data-ng-if="request.created"></friendlydate>

或者您可以在指令中使用scope.$watch:

myApp.directive('friendlydate', function () {
function link(scope, element, attrs) {
scope.$watch(function () {
console.log(scope);
console.log(scope.date);
var uglydate = scope.date;
//do stuff
scope.formatteddate = prettydate;
});
};

return {
restrict: 'E',
scope: {
date: '@'
},
link: link,
template: '{{formatteddate}}'
};

});

关于javascript - Angularjs 指令 - 无法从隔离范围中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com