AngularJS - 从子指令访问父指令属性

时间:2013-11-26 08:57:30

标签: angularjs angularjs-directive

这不应该是一件难事,但我无法弄清楚如何最好地做到这一点。

我有一个父指令,如下所示:

directive('editableFieldset', function () {
  return {
    restrict: 'E',
    scope: {
      model: '='
    },
    replace: true,
    transclude: true,

    template: '
      <div class="editable-fieldset" ng-click="edit()">
        <div ng-transclude></div>

        ...

      </div>',

    controller: ['$scope', function ($scope) {
      $scope.edit = ->
        $scope.editing = true

       // ...
    ]
  };
});

儿童指令:

.directive('editableString', function () {
  return {
    restrict: 'E',
    replace: true,

    template: function (element, attrs) {
      '<div>
        <label>' + attrs.label + '</label>
        <p>{{ model.' + attrs.field + ' }}</p>

        ...
      </div>'
    },
    require: '^editableFieldset'
  };
});

如何从child指令轻松访问父指令的modelediting属性?在我的链接函数中,我可以访问父作用域 - 我应该使用$watch来查看这些属性吗?

放在一起,我想拥有的是:

<editable-fieldset model="myModel">
  <editable-string label="Some Property" field="property"></editable-string>
  <editable-string label="Some Property" field="property"></editable-string>
</editable-fieldset>

这个想法是默认显示一组字段。如果单击,它们将成为输入并可以进行编辑。

2 个答案:

答案 0 :(得分:8)

this SO post获取灵感,我得到了一个有效的解决方案here in this plunker

我不得不改变一下。我选择在editableString上也有一个孤立的范围,因为更容易将正确的值绑定到模板。否则,您将不得不使用compile或其他方法(例如$transclude服务)。

结果如下:

<强> JS:

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function($scope) {

  $scope.myModel = { property1: 'hello1', property2: 'hello2' }

});


myApp.directive('editableFieldset', function () {
  return {
    restrict: 'E',
    scope: {
      model: '='
    },
    transclude: true,
    replace: true,
    template: '<div class="editable-fieldset" ng-click="edit()"><div ng-transclude></div></div>',
    link: function(scope, element) {
      scope.edit = function() {

        scope.editing = true;
      }
    },
    controller: ['$scope', function($scope) {

      this.getModel = function() {
        return $scope.model;
      }

    }]
  };
});

myApp.directive('editableString', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      label: '@',
      field: '@'
    },
    template: '<div><label>{{ label }}</label><p>{{ model[field] }}</p></div>',
    require: '^editableFieldset',
    link: function(scope, element, attrs, ctrl) {

      scope.model = ctrl.getModel();
    }
  };
});

<强> HTML:

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <editable-fieldset model="myModel">
      <editable-string label="Some Property1:" field="property1"></editable-string>
      <editable-string label="Some Property2:" field="property2"></editable-string>
    </editable-fieldset>
  </body>

答案 1 :(得分:8)

您可以通过在子指令链接函数

中传递属性来访问父控制器
link: function (scope, element, attrs, parentCtrl) {
    parentCtrl.$scope.editing = true;
}