javascript - angular指令的隔离作用域问题
本文介绍了javascript - angular指令的隔离作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
**指令中的scope:{}时不是会创建隔离作用域,指令隔离作用域内不能访问父作用域的属性,然而这个竟然能,望高手指点一二,刚上手angular-----**
<div ng-init="myProperty = 'wow, this is cool'"></div>
Surrounding scope: {{ myProperty }}
<div my-inherit-scope-directive>
Inside an directive with inherited scope: {{ myProperty }}
</div>
<div my-directive>
Inside myDirective, isolate scope: {{ myProperty }} **//这里的myProperty竟然也能访问父作用域的myProperty**
<div>
<script>
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {}
};
})
.directive('myInheritScopeDirective', function() {
return {
restrict: 'A',
scope: true
};
})
</script>
解决方案
你应该这么写:
//当然html中就不需要写template中的部分了。
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {},
template:"Inside myDirective, isolate scope: {{ myProperty }}"
};
})
按照你的写法,添加了指令的元素并没有按照你的设计被编译。
或者干脆这么写
.directive('mysss', function() {
return {
restrict: 'A',
scope: {},
replace : true,
template:"<div>Inside an directive with inherited scope: {{ myProperty }}</div>"
};
})
//replace:true时,添加了指令的元素会被template内内容整体替换。
这篇关于javascript - angular指令的隔离作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文