How can an Angular directive compile() function access an isolated scope?

拟墨画扇 提交于 2019-12-04 10:04:21

This doesn't work because {{example}} is being evaluated against the parent scope, which makes sense, since you are essentially changing the element before compilation to:

<div>{{example}}<div>

You can verify by replacing '$scope.example =' with '$scope.$parent.example =' (for demonstration purposes only - it's not a best practice to use $parent).

What you are really trying to do is something similar to transclusion, but there are very easier ways to do it. For instance:

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);
      };
    }
  };
});

When you use a template, it replaces the content of the element the directive is applied to (unless you use replace: true, in which case it replaces the entire element), and the contents of the template are evaluated against the directive scope.

You could do what you are trying to do using the transclude parameter passed to compile (see the docs), but this has been deprecated so I wouldn't recommend going down that road.

Here's a Plunk where you can play with some variations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!