gpt4 book ai didi

javascript - 对 AngularJS 中指令之间的范围继承感到困惑

转载 作者:行者123 更新时间:2023-11-28 06:48:02 24 4
gpt4 key购买 nike

我想知道如何实现指令之间的范围继承。

例如:

<html ng-app="app">
<head>
<title>TEST DRAG</title>
</head>
<body ng-controller="main">

<dragcont>
<dragitem></dragitem>
</dragcont>



<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">

(function(){

var app = angular.module("app", []);

app.controller("main", function($scope){
$scope.name = "Hello";
})
.directive("dragcont", function(){
return {
restrict: "AE",
scope: {

},
controller: function($scope){
$scope.name = "dragcont";
},
link: function(scope, EL, attrs){

}
}
})
.directive("dragitem", function(){
return {
restrict: "AE",
controller: function($scope){
console.log($scope.name);
},
link: function(scope, EL, attrs){

}
}
})


})()

</script>
</body>
</html>

当我运行它时,它总是打印 Hello。看起来dragitem可以继承主 Controller 的作用域,但是如果我想让它继承dragcont怎么办?

最佳答案

隔离范围用于将指令的内部工作与其使用“隔离”。因此,作用域既不能从其父级继承,也不能被子指令和表达式继承。

所以,对于分离株 foo指令:

.directive("foo", function(){
return {
scope: {},
link: function(scope){
scope.inner = "hidden from outside";
}
}
})

子指令和表达式不会继承其隔离范围。

<foo>
<span>{{inner}} will be undefined</span>
</foo>

使用 template :

另一方面,template指令 foo该指令的作者已知,因此它确实使用了isolate作用域。如果 foo 则以下内容会起作用有一个模板:

scope: {},
template: '<span>{{inner}}</span>',
link: function(scope){
scope.inner = "hidden from outside";
}

使用手动“嵌入”:

有时,允许指令的用户指定自定义模板是有意义的。该指令的作者可能还希望公开特殊的“神奇”变量以在自定义模板中使用,这与 $index 不同。 , $first等.. ng-repeat .

这可以通过手动嵌入来完成:

scope: {},
transclude: true,
template: '<div>{{header}}</div>\
<placeholder></placeholder>',
link: function(scope, element, attrs, ctrls, transclude){
scope.header = "I am foo"; // still only visible in the template

// create a new scope, that inherits from parent, but a child of isolate scope
var anotherScope = scope.$parent.$new(false, scope);
anotherScope.$magic = "magic";

// transclude/link against anotherScope
transclude(anotherScope, function(clonedContents){
element.find("placeholder").replaceWith(clonedContents);
}
}

现在,您可以访问$magic嵌入内容内和外部范围内的变量(假设它有 $scope.name = "John" )

<foo>
<div>I can see {{name}} and {{$magic}}</div>
</foo>

生成的 DOM 将是:

<foo>
<div>I am foo</div>
<div>I can see John and magic</div>
</foo>

关于javascript - 对 AngularJS 中指令之间的范围继承感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225435/

24 4 0
文章推荐: ios - 与 SWIFT 同步键值信息的简便方法
文章推荐: c++ 输入一个字符串——不是用 getline() 而是用 cin
文章推荐: html - 容器中需要隐藏的溢出使滚动条出现
文章推荐: javascript - 如何从动态