【问题标题】:Accessing scope property inside directive访问指令内的范围属性
【发布时间】:2015-01-11 23:33:07
【问题描述】:

我正在调用指令:

<latest-survey survey="latestSurvey"></latest-survey>

我的指令的代码是:

function latestSurvey(){
    return {
        restrict: 'E',
        templateUrl: 'js/modules/survey/latest.html',
        scope: {
            survey: '=survey'
        },
        link: function(scope, element, attrs){
            console.log(scope);
            console.log(scope.survey);
        }
    }
}

console.log(scope) 行输出范围:

Scope {$id: "007", $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null…}
$$asyncQueue: Array[0]
$$childHead: null
$$childTail: null
$$destroyed: false
$$isolateBindings: Object
$$listenerCount: Object
$$listeners: Object
$$nextSibling: 
$$childScopeClass
$$phase: null
$$postDigestQueue: Array[0]
$$prevSibling: null
$$watchers: Array[3]
$id: "007"
$parent: 
$$childScopeClass
$root: Scope
survey: Object
this: Scope
__proto__: Scope

如您所见,survey 列在那里,我可以在控制台中浏览它以查看其属性。但是,下一行console.log(scope.survey) 输出:

undefined

如何在作用域内访问这个对象?

【问题讨论】:

  • 如果在指令模板中使用{{survey}} 会发生什么?
  • 列出调查对象。我可以在模板中访问它,但由于某种原因不能在链接功能中访问。
  • 看起来非常好。尝试发布 sn-p 或小提琴?
  • 尝试将您的控制台日志 od scope.survey 包装到 $timeout 中,并在超时 0 和 100 中显示您所拥有的内容。

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

调查是否在控制器中异步加载(latestSurvey)? scope.surveyundefined 的原因之一可能是因为请求未完成并且项目为空。

我建议您尝试使用一些虚拟数据设置$scope.latestSurvey,看看问题是否仍然存在。

【讨论】:

  • 是的,它是异步加载的。当它进来时,我怎样才能让它更新指令范围?
  • 您可以使用“@”而不是“=”,或者您可以添加一个加载屏幕并隐藏内容,然后在 Promise 完成时显示它。您必须使用 angularjs $interceptor。到目前为止我见过的最好的实现是this。或者你可以使用$watch 来查看内容是否发生了变化,但是使用$watch 是不良架构的标志,通常
  • @babbaggeii 这个建议本质上是我的回答
  • @salniro 我在使用“@”时遇到了一些问题,有时不得不添加$watch:/。但我也赞成你的:)
  • 在这种情况下,attrs 上的 @CristiBerceanu $observe 可能更合适,但无论哪种方式。我进行了编辑以将其包含在 OP 中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
相关资源
最近更新 更多