3

考虑以下:

HTML

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<meta charset=utf-8 />
<title>Exploring directives</title>
</head>
<body> 

  <my-directive>
    Some text
  </my-directive>
  {{Info.Version}}
  <script type="text/ng-template" id='my-directive.html'>
    <div>Hello, {{Info.Version}}</div>
  </script>
</body>
</html>

JS

var app = angular.module('myApp', []);
app.run(function($rootScope) {
  $rootScope.Info = {};
  $rootScope.Info.Name = 'rootScope';
  $rootScope.Info.Version = '1.0.0.1';
});
app.directive('myDirective', function() {
  return {    
    restrict: 'E',
    templateUrl: 'my-directive.html',
    scope: false
  };
});

巴达朗

在此处输入图像描述

据我所见, $rootScope 从未显示(但我猜如果是的话,它会被标记为Scope (001))。

当我在JS中将范围更改为 true 时:

app.directive('myDirective', function() {
  return {    
    restrict: 'E',
    templateUrl: 'my-directive.html',
    scope: true
  };
});

似乎$ rootScope被下推到Scope (002)

在此处输入图像描述

有人可以解释发生了什么吗?为什么 $rootScope 似乎被推倒了?那上面是什么?这是 jsbin 链接:http: //jsbin.com/udALigA/1/

4

1 回答 1

0

通常指令会创建自己的scope(在这种情况下Scope (002)),但是当您设置它时scope: truemyDirective它将继承scope父元素的。

至少,这就是我假设在这里发生的事情,因为我以前从未见过这样做过。通常你会使用作用域在你的指令中定义某些变量,这样你就可以使用 html 标签传递参数,如下所示:

<my-directive someVar="true">
  Some text
</my-directive>

然后您可以使用以下命令将 的值拉someVar入指令中:

scope: {
  someVar: '@' //or '=' if you wanted two-way binding
}

然后您可以someVar在链接到指令的控制器中使用。

拉低父元素范围的一种更常见的方法是使用transclude指令中的赋值:

transclude: true
于 2014-06-02T14:49:13.997 回答