我已经使用以下定义
创建了一个指令LastMeet.directive("progressBar", function() {
return {
restrict: "A",
scope: {
meeting: "&meeting"
},
link: function(scope, elm, attrs) {
var meeting = scope.meeting();
// Gather the details we need about this meeting
var startDate = scope.meeting().start_datetime;
var deadline = scope.meeting().deadline;
var complete = scope.meeting().percentage_complete;
console.log(meeting);
console.log(meeting["start_datetime"]);
// No point doing anything if we're already at 100%
if (complete < 100.0) {
// Calculate how much to increment by every second
var diff = deadline - startDate;
var increment = diff / 60.0;
var timer;
scope.percentage = complete;
scope.onTimeout = function() {
if (scope.percentage < 100.0) {
scope.percentage += increment;
elm.css({ right: 100 - percentage + "%" });
timer = $timeout(scope.onTimeout, 1000);
}
}
// Setup our timer and get going :)
timer = $timeout(scope.onTimeout, 1000);
}
}
}
})
会议属性是具有许多不同属性的对象。正如您所看到的,我添加了2个控制台输出,一个用于会议本身,另一个用于我正在尝试访问的属性。我的控制台有以下输出
b {$resolved: false, $then: function, $get: function, $save: function, $query: function…}
$resolved: true
$then: function (callback, errback) {
agenda_items: Array[2]
deadline: 1365897600
description: "Meeting to discuss the progress of LastMeet"
faye_token: "7468585e529849ca992efbd3b9de6337"
icon: null
id: 20
name: "LastMeet"
percentage_complete: 100
start_datetime: 1365897600
__proto__: b
这是会议对象的输出,它清楚地显示了包含的start_datetime
属性。然而,第二个控制台输出只是
undefined
为什么会议对象在那里,我可以看到所有内容,但是当我尝试访问包含的属性时,我每次都会得到未定义的内容?
答案 0 :(得分:2)
SUCCESS!因此,当指令运行时,变量未完全准备好似乎是一个问题。它正在查看的会议对象是通过resource
创建的,它在获取服务器数据时创建占位符对象,然后填充对象。
我的猜测是,有角度地看到物体存在(实际上是占位符),但我想要的值实际上并不存在。不知道为什么控制台输出显示它们在那里但是很好。为了解决这个问题,我在对象中添加了一个watch
语句,当它实际发生变化并被填充时会被删除。我的指令现在看起来像这样
LastMeet.directive("progressBar", function($timeout) {
return {
restrict: "A",
scope: {
meeting: "=meeting"
},
link: function(scope, elm, attrs) {
unwatch = scope.$watch('meeting', function(meeting) {
if (meeting) {
// Gather the details we need about this meeting
var startDate = meeting.start_datetime;
var deadline = meeting.deadline;
var complete = meeting.percentage_complete;
// No point doing anything if we're already at 100%
if (complete < 100.0) {
// Calculate how much to increment by every second
var diff = deadline - startDate;
var increment = diff / 60.0;
var timer;
scope.percentage = complete;
scope.onTimeout = function() {
if (scope.percentage < 100.0) {
scope.percentage += increment;
elm.css({ right: 100 - scope.percentage + "%" });
timer = $timeout(scope.onTimeout, 1000);
}
}
// Setup our timer and get going :)
timer = $timeout(scope.onTimeout, 1000);
}
unwatch();
}
}, true)
}
}
})
现在我有一些计算问题,但它正在运行:)