gpt4 book ai didi

angularjs - Angular 指令 compile() 函数如何访问隔离的作用域?

转载 作者:行者123 更新时间:2023-12-04 19:04:28 25 4
gpt4 key购买 nike

我有以下指令:

angular.module("example_module", [])
.directive("mydirective", function() {
return {
scope: { data: "@mydirective" }
compile: function(element) {
element.html('{{example}}');
return function($scope) {
$scope.example = $scope.data + "!";
};
}
};
});

以及以下 HTML 代码:
<!DOCTYPE html>
<html ng-app="example_module">
<head>
<meta charset="utf-8">
<title>Example title</title>
<script src="lib/angular/angular.min.js"></script>
<script src="js/example.js"></script>
</head>
<body>
<div mydirective="Hello world"></div>
</body>
</html>

我希望指令编译为 Hello world! ,但它会编译为空字符串。 scope创建一个孤立的范围,对于 {{example}} 来说似乎不可能达到.

我想知道 compile() 创建的新 HTML 代码如何可以访问链接功能 $scope .

最佳答案

这不起作用,因为 {{example}} 正在针对父作用域进行评估,这是有道理的,因为您实际上是在编译之前将元素更改为:

<div>{{example}}<div>

您可以通过将 '$scope.example =' 替换为 '$scope.$parent.example =' 进行验证(仅用于演示目的 - 使用 $parent 不是最佳做法)。

你真正想做的是类似于嵌入的事情,但有更简单的方法来做到这一点。例如:
angular.module("example_module", [])
.directive("mydirective", function() {
return {
restrict: 'A',
scope: { data: "@mydirective" },
template: '{{example}}',
compile: function(element) {
return function($scope) {
console.log($scope.data);
$scope.example = $scope.data + "!";
console.log($scope.example);
};
}
};
});

当您使用模板时,它会替换指令所应用到的元素的内容(除非您使用 replace: true,在这种情况下它会替换整个元素),并且会针对指令范围评估模板的内容。

您可以使用传递给 compile ( see the docs ) 的 transclude 参数来执行您想要执行的操作,但是这已被弃用,因此我不建议沿着这条路走下去。

Here's a Plunk你可以在这里玩一些变化。

关于angularjs - Angular 指令 compile() 函数如何访问隔离的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28728324/

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