gpt4 book ai didi

javascript - AngularJS Directive controllerAs 语法和作用域

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:24:41 25 4
gpt4 key购买 nike

这是我的代码:

//HTML

<body>
<h1>{{foo.name}}</h1>

<my-directive></my-directive>
</body>

//脚本

app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: true, //**********
template: '<h4>{{foo.name}}</h4>',
controllerAs: 'foo',
controller: fooCtrl,
link: function(scope) {
console.log(scope);
}
}
});

var fooCtrl = function() {
this.name = 'FOO';
}

我的问题:

如果我使用 controllerAs 语法并且不在 myDirective 中设置 scope: true,则 Controller 将变为全局,因此 Controller 会将 foo.name 插入到 Tag 中。但是一旦我将范围设置为 true, Controller 将只应用于 myDirective。

这怎么会发生?指令内部的 Controller 是否会创建一个从周围范围继承的新范围?为什么会适用于全局?

更新

这是一个非常愚蠢的问题,因为我之前一直使用isolate scope,所以忘记scope inside directive的用法,阅读文档并清楚地理解。谢谢解答

最佳答案

我猜你问的是 Angular 指令中的范围属性。另外我假设你的意思是 $rootScope 术语“全局”。如 this guide 中所述,在指令中,范围属性的行为如下,

scope.false

The default option which does not create a new scope for a directive but shares the scope with its parent

作用域.true

Creates a new scope but prototypically inherits from the parent scope.

范围:‘隔离’

Creates an isolated scope which does not prototypically inherit from the parent scope but you can access parent scope using scope.$parent

关于javascript - AngularJS Directive controllerAs 语法和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678067/

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