简体   繁体   English

AngularJS 范围未在指令中更新

[英]AngularJS scope not updating in directive

I have an AngularJS directive that needs an isolate scope plus access to the $parent scope.我有一个 AngularJS 指令,它需要一个隔离范围以及对$parent范围的访问。 The parent scope has data which changes after an ajax call completes.父作用域具有在 ajax 调用完成后发生变化的数据。

In my directive's linking function, I have:在我的指令的链接函数中,我有:

scope.loading = scope.$parent.contractData.People.loading;

but when the parent's contractData value changes, scope.loading does not update.但是当父的contractData值发生变化时, scope.loading不会更新。 I've even tried using scope.$watch , but that does not get notified of the change either.我什至尝试使用scope.$watch ,但也没有收到更改通知。

In my directive's template, I am using ng-show .在我的指令模板中,我使用的是ng-show The following template works as expected:以下模板按预期工作:

<span ng-show="$parent.contractData.People.loading">loading</span>

But this does not work (because the scope never finds out about the data change):但这不起作用(因为范围永远不会发现数据更改):

<span ng-show="loading">loading</span>

I need to be able to set up a scope variable in my directive, because 'People' will change, depending on data passed into the directive's attributes.我需要能够在我的指令中设置一个范围变量,因为“人”会改变,具体取决于传递到指令属性的数据。 Otherwise I would just stick with the working example above.否则我只会坚持上面的工作示例。

Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

You can set up the HTML for the directive like:您可以为指令设置 HTML,例如:

<div mydirective="contractData.People.loading"></div>

And within the directive itself, create an isolate scope binding to the loading property在指令本身内,创建一个隔离范围绑定到loading属性

scope: {
    isLoading: '=mydirective'
},
// rest of directive

This creates a property on the directive's local scope that is bound to the attribute expression.这会在指令的本地范围内创建一个绑定到属性表达式的属性。 Then you can refer to that scope property in the directive's template like:然后您可以在指令的模板中引用该范围属性,例如:

template: '<span ng-show="isLoading">loading</span>'

Here is a fiddle这是一个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM