angularjs – Angular指令compile()函数如何访问隔离范围?
发布时间:2020-12-17 17:38:38 所属栏目:安全 来源:网络整理
导读:我有以下指令: angular.module("example_module",[]).directive("mydirective",function() { return { scope: { data: "@mydirective" } compile: function(element) { element.html('{{example}}'); return function($scope) { $scope.example = $scope.da
我有以下指令:
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!,但它编译为空字符串.范围创建了一个孤立的范围,似乎无法达到{{example}}. 我想知道compile()创建的新HTML代码如何访问链接函数$??scope. 解决方法
这不起作用,因为{{example}}正在针对父作用域进行评估,这是有道理的,因为您实际上是在编译之前将元素更改为:
<div>{{example}}<div> 您可以通过将’$scope.example =’替换为’$scope.$parent.example =’进行验证(仅用于演示目的 – 使用$parent不是最佳做法). 你真正想要做的是类似于翻译,但有更简单的方法来做到这一点.例如: angular.module("example_module",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你可以玩一些变化. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |