<!doctype html>
<html ng-app="myApp">
<head>
<script src="lib/angular.js"></script>
</head>
<body>
<div ng-init="myProperty = 'wow, this is cool'"></div>
Surrounding scope: {{ myProperty }}
<div my-inherit-scope-directive="SomeCtrl">
Inside an directive with inherited scope: {{ myProperty }}
</div>
<div my-directive>
Inside myDirective, isolate scope: {{ myProperty }}
</div>
<script>
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {}
};
})
.directive('myInheritScopeDirective', function() {
return {
restrict: 'A',
scope: true
};
})
</script>
</body>
</html>
自定义指令myDireective应该是拥有独立scope域的,那以他为属性的div块应该访问不到全局域中的myProperty 才对,可是在chrome上照样可以显示Inside myDirective, isolate scope: wow, this is cool,而在一个在线编译器JS Bin上却不会显示表达式{{ myProperty }}的值wow, this is cool,实在是不懂这是为什么。
先上两个例子,请注意比较:
区别仅仅是
Name: {{customer.name}} Address: {{customer.address}}
的位置不同,写法1其实就是你的写法,这时候customer.name
读取的是控制器下的scope
,所以能读取到内容;写法2是你想要的写法--作用域隔离,此时不会渲染出对应的内容。至于原因,在文档上有这么一段话:
简单的来说,就是控制器和指令都有作用域scope,但是是相互分离的,你想要实现指令具有隔离的scope,所以应该把渲染内容写到指令的模板中去