【问题标题】:Can't find $parent scope's objects in Angular directive在 Angular 指令中找不到 $parent 范围的对象
【发布时间】:2015-07-05 06:03:39
【问题描述】:

在我的自定义指令中,我需要访问对象 $scope.$parent.users。

如果我 console.log $scope.$parent:

pillbox_directives.directive('scheduleCell', function(){
        return {
            restrict: 'EA',
            link: function($scope, element, attrs){
                console.log($scope.$parent);        
            }
        }
    });

...然后记录所需的 $parent,它包含预期的对象“用户”:

$$ChildScope: function b() {this.$$watchers=this.$$nextSibling=this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$id=++ob;this.$$ChildScope=null;}
$$childHead: n
$$childTail: n
$$listenerCount: Object
$$listeners: Object
$$nextSibling: null
$$prevSibling: null
$$watchers: Array[4]
$$watchersCount: 0
$id: 2
$parent: n
cloneDrop: function ($index) {
deadDrop: function ($index) {
generateSchedule: function (day) {
logOff: function () {
notSorted: function (obj) {
setup: Array[2]
users: Array[2]
__proto__: n

但是,如果我使用 console.log($scope.$parent.users),它会记录“未定义”

关于为什么我无法以这种方式访问​​ $scope.$parent.users 有什么想法吗?

【问题讨论】:

  • 我们需要更多信息。 users 数组可能在控制台日志后发生变化,当您在开发工具中展开该数组时,您会看到新填充的数据,但是当您直接在控制台记录 users 时,它没有任何价值。也许您是通过 ajax 请求获取它?
  • 参考this
  • @OmriAharon 当页面/控制器加载时,用户数组是从带有 $http.get 的 mongo 数据库填充的。您是说在指令尝试记录它时数组可能尚未填充?
  • @RayonDabre 我认为在我解决了这个紧迫的问题后,该链接将对我有用。但是,我没有看到它如何应用于这个问题。你介意向我指出我错过了什么吗?谢谢
  • @dt801ts 这正是我要说的:)

标签: javascript angularjs


【解决方案1】:

用户数组使用来自控制器的 $http.get 调用填充,并且在指令尝试 console.log($scope.$parent.users) 时尚未完成填充

解决方案是将 ng-if="users" 添加到指令元素中,以确保“用户”存在并在指令加载之前加载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多