在Angular指令中找不到$parent作用域的对象。

10 浏览
0 Comments

在Angular指令中找不到$parent作用域的对象。

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

如果我控制台输出$scope.$parent:

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

...然后所需的$parent被记录下来,并且按预期包含一个对象'users':

$$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

然而,如果我控制台输出($scope.$parent.users),它会返回'undefined'。

你们有什么想法,为什么我无法以这种方式访问$scope.$parent.users?

0
0 Comments

在Angular指令中无法找到父级作用域对象的问题

问题的原因是,用户数组是通过控制器中的$http.get调用进行填充的,而在指令尝试使用console.log($scope.$parent.users)输出时,用户数组还没有完成填充。

解决方法是在指令元素中添加ng-if="users",以确保在指令加载之前'users'存在并已加载。

下面是解决方法的代码示例:


通过添加ng-if指令并设置条件为"users",我们确保了指令只在'users'存在且已加载时才会被渲染和执行,从而避免了无法找到父级作用域对象的问题。

通过以上解决方法,我们可以在指令中访问到正确的父级作用域对象,并继续进行后续操作。

0