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>
阅读 1.7k
1 个回答

你应该这么写:

//当然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内内容整体替换。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题