Angular directive - what if scope is not set?

我与影子孤独终老i 提交于 2019-12-12 04:34:59

问题


How are scope attributes being inherited when scope is not set in Angular directive definition?

In Angular docs (under 'Directive Definition Object') there are two cases: when scope is true or when scope is an object ({}). What if scope is not set or is false. How are attributes inherited in this case for the scope and for it's children?


回答1:


When scope is set to false(also default value) in directive definition, behavior of scope differs based on whether you are doing transclusion or not.

If you do not transclude, it pretty much uses parent scope. Just as if you did not used a directive and written the linked template directly in the page.

Fiddle

Transclusion always creates a child scope but it's bound to parent scope in a strange way when the directive scope is false. You can "read" parent scope but as soon as you "write" to a property it's not bound to parent scope's same property anymore but now a property on child scope unless that property is an object.

Transcluded Fiddle

Child scope is the ones in green border.

Try changing the parent scope first. Enter something in the "var" input field, you will see that the child scope's var will also change. But when you change var in child scope it's not changing the parent scope, and changing the var in parent scope does not affect child scope as the bond is broken when you wrote to var from child scope. This does not apply to the objects (try the same on sp.var, you will see that you cannot break the "bond"). According to developers this is the expected and/or intended behavior.




回答2:


If the scope is set to false (which is the default) then the directive has the same scope as the parent- no new scope is created. Since they share a scope any changes in the parent will be reflected in the directive and vice-versa.

Since this isn't great from an encapsulation standpoint, many recommend using an isolate scope whenever possible (an isolate scope being when you set the scope to {})



来源:https://stackoverflow.com/questions/19346275/angular-directive-what-if-scope-is-not-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!