AngularJS自定义指令scope参数的问题?

<!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,实在是不懂这是为什么。

阅读 2.5k
1 个回答

先上两个例子,请注意比较:

//写法1:
<body>
  <div ng-app="myApp" ng-controller="myCtrl">
  <my-customer>
    Name: {{customer.name}}  Address: {{customer.address}} //模板内容位置1
  </my-customer>
</div>
</body>
<script>
  angular.module('myApp', [])
    .controller('myCtrl', ['$scope', function ($scope) {
      $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
      };
    }])
    .directive('myCustomer', function () {
      return {
        restrict: 'E',
        scope:{}
      };
    });
</script>
//写法2
<body>
  <div ng-app="myApp" ng-controller="myCtrl">
  <my-customer>
 
  </my-customer>
</div>
</body>
<script>
  angular.module('myApp', [])
    .controller('myCtrl', ['$scope', function ($scope) {
      $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
      };
    }])
    .directive('myCustomer', function () {
      return {
        restrict: 'E',
        scope:{},
         template: 'Name: {{customer.name}}  Address: {{customer.address}}'//模板内容位置2
      };
    });
</script>

区别仅仅是Name: {{customer.name}} Address: {{customer.address}}的位置不同,写法1其实就是你的写法,这时候customer.name读取的是控制器下的scope,所以能读取到内容;写法2是你想要的写法--作用域隔离,此时不会渲染出对应的内容。

至于原因,在文档上有这么一段话:

Both controllers and directives have reference to the scope, but not to each other. This arrangement isolates the controller from the directive as well as from the DOM. This is an important point since it makes the controllers view agnostic, which greatly improves the testing story of the applications.

简单的来说,就是控制器和指令都有作用域scope,但是是相互分离的,你想要实现指令具有隔离的scope,所以应该把渲染内容写到指令的模板中去

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进