自定义指令中的问题

Issue in Custom Directives

在下面的代码中,我添加了一个控制器来存储可以在子作用域中使用的名称,而无需使用 prelinks.But 名称值仍然是 undefined.Where 我错了吗。

<!DOCTYPE html>
<html ng-app="test">

<head>
  <title>AngularJS</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.min.js">
  </script>
</head>

<body>
  <parent></parent>
</body>
<script>
  var test1 = angular.module("test", []);
  test1.directive("child", function() {
    return {
      restrict: "E",
      template: "<div>{{message1}}</div>",
      link: function(scope, ctrl) {
        scope.message1 = "i m child of " + ctrl.name;
      }
    }
  });
  test1.directive("parent", function() {
    return {
      restrict: "E",
      template: "<div style='color:red'>{{message}}{{name}}" + "<child></child>" + "   </div>",
      link: function(scope, ctrl) {
        scope.name = ctrl.name;
        alert(ctrl.name);
        scope.message = "hi i am parent ";
      },
      controller: function() {
        this.name = "aditya";
      }
    }
  });
</script>

</html>

当您使用 controller as 语法 this 声明 parent 控制器时,您可以将 controllerAs 选项添加到指令并定义控制器的名称:

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

test1.directive("child", function() {
    return {
      restrict: "E",
      template: "<div>{{message1}}</div>",
      link: function(scope) {
        scope.message1 = "i m child of " + scope.parentCtrl.name;
      }
    }
  });

test1.directive("parent", function() {
    return {
      restrict: "E",
      template: "<div style='color:red'>{{message}}{{name}}" + "<child></child>" + "   </div>",
      link: function(scope, element, attrs, ctrl) {
        scope.name = ctrl.name;
        alert(scope.name);
        scope.message = "hi i am parent ";
      },
      controller: function($scope) {
        this.name = "aditya";
      },
        controllerAs: 'parentCtrl' // Name of the controller
    }
  });

然后,在您的 child 中,您可以使用其定义的名称 scope.parentCtrl.name 访问 parent 范围。