自定义指令中的问题

时间:2015-01-22 09:20:51

标签: angularjs angularjs-directive

在下面的代码中,我添加了一个控制器来存储可以在子范围内使用的名称,而不使用prelinks.But仍然是名称值未定义。我在哪里出错。

<!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>

1 个答案:

答案 0 :(得分:1)

当您使用controller as语法this声明父控制器时,可以向指令添加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
    }
  });

然后,在您的孩子中,您可以使用其定义的名称scope.parentCtrl.name来访问父作用域。