【发布时间】:2014-11-19 10:39:15
【问题描述】:
我正在使用 Angular.js 和 Firebase API 按照this tutorial 中的步骤制作滑块。
我在指令文件中创建了一个指令“滑块”,代码如下:
.directive('slider', function()
{
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.currentIndex = 0; // Initially the index is at the first slide
scope.next = function()
{
scope.currentIndex < scope.challenges.length - 1 ? scope.currentIndex++ : scope.currentIndex = 0;
};
scope.prev = function()
{
scope.currentIndex > 0 ? scope.currentIndex-- : scope.currentIndex = scope.challenges.length - 1;
};
scope.$watch('currentIndex', function()
{
scope.challenges.forEach(function(challenge)
{
challenge.visible = false; // make every challenge invisible
});
scope.challenges[scope.currentIndex].visible = true; // make the current challenge visible
});
},
template: '<div></div>'
};
如您所见,我没有隔离范围,因此它应该从父级获取 scope.challenges,但它作为未定义的值而不是来自 Firebase 的数据。
这样做 forEach of undefined 会引发错误: TypeError:无法读取未定义的属性“forEach”
我花了大约 3 个小时试图了解范围,一个解决方案将是非常有益的。 非常感谢。
【问题讨论】:
-
你能分享创建挑战的代码吗?你提到了 firebase,所以我想有一些异步操作正在发生?
-
替代 angular.forEach(scope.challenge, function(challenge) { challenge.visible = false });
-
@Kato 在控制器中我有
$scope.findAll = function() { $scope.challenges = Challenge.findAll(); };它只是从 Firebase 获取所有结果。 -
@DeadCalimero 我已经尝试过了,但由于 scope.challenges 仍未定义,我也尝试过 $watch 挑战以检查它是否是异步的。
-
@angglada 肯定是一个承诺,Challenge.findAll() 请求一个带有 $http 的 url。你在迭代之前解决了承诺吗?
标签: javascript angularjs angularjs-scope firebase