我有以下指令:
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}}.
解决方法
这不起作用,因为{{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你可以玩一些变化.