【问题标题】:Scope creation and batarang范围创建和batarang
【发布时间】:2014-02-24 14:58:01
【问题描述】:

考虑以下几点:

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/

【问题讨论】:

  • 你有没有弄清楚为什么 rootScope 没有出现,或者为什么它的 id 是 002 而不是 001?
  • 还没有,但想听听答案。

标签: angularjs batarang


【解决方案1】:

通常指令会创建自己的scope(在本例中为Scope (002)),但是当您在myDirective 中设置scope: true 时,它将继承父元素的scope

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

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

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

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

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

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

transclude: true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多