gpt4 book ai didi

angularjs - 范围创建和 batarang

转载 作者:行者123 更新时间:2023-12-03 06:46:22 25 4
gpt4 key购买 nike

考虑以下因素:

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
};
});

巴塔朗

enter image description here

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

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

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

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

enter image description here

有人可以解释一下发生了什么吗?为什么 $rootScope 看起来被推低了?那么它上面是什么?这是 jsbin 链接:http://jsbin.com/udALigA/1/

最佳答案

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

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

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

然后您可以使用以下方法将 someVar 的值提取到指令中:

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

然后您可以在链接到该指令的 Controller 中使用 someVar

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

transclude: true

关于angularjs - 范围创建和 batarang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21488132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com