12

我不确定这是执行此操作的方法,但我的目标如下:

  • 我有一个父指令
  • 在父指令的块内,我有一个子指令,它将从用户那里获得一些输入
  • 子指令将在父指令的范围内设置一个值
  • 我可以从那里拿走

当然,问题在于父指令和子指令是同级的。所以我不知道该怎么做。注意 - 我不想在

小提琴:http: //jsfiddle.net/rrosen326/CZWS4/

html:

<div ng-controller="parentController">
    <parent-dir dir-data="display this data">
        <child-dir></child-dir>
    </parent-dir>
</div>

Javascript

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

testapp.controller('parentController', ['$scope', '$window', function ($scope, $window) {
    console.log('parentController scope id = ', $scope.$id);
    $scope.ctrl_data = "irrelevant ctrl data";
}]);

testapp.directive('parentDir', function factory() {
    return {
        restrict: 'ECA',
        scope: {
            ctrl_data: '@'
        },
        template: '<div><b>parentDir scope.dirData:</b> {{dirData}} <div class="offset1" ng-transclude></div> </div>',
        replace: false,
        transclude: true,
        link: function (scope, element, attrs) {
            scope.dirData = attrs.dirData;
            console.log("parent_dir scope: ", scope.$id);
        }
    };
});

testapp.directive('childDir', function factory() {
    return {
        restrict: 'ECA',
        template: '<h4>Begin child directive</h4><input type="text"  ng-model="dirData" /></br><div><b>childDir scope.dirData:</b> {{dirData}}</div>',
        replace: false,
        transclude: false,
        link: function (scope, element, attrs) {
            console.log("child_dir scope: ", scope.$id);
            scope.dirData = "No, THIS data!"; // default text
        }
    };
});
4

2 回答 2

27

如果你想要那种通信,你需要require在 child 指令中使用。这将需要父级controller,因此您需要一个controller具有您希望子级指令使用的功能的那里。

例如:

app.directive('parent', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div>{{message}}<span ng-transclude></span></div>',
    controller: function($scope) {
      $scope.message = "Original parent message"

      this.setMessage = function(message) {
        $scope.message = message;
      }
    }
  }
});

控制器中有一条消息,$scope您有一种方法可以更改它。

为什么$scope一对一使用this?您无法访问$scope子指令中的 ,因此您需要this在函数中使用,以便您的子指令能够调用它。

app.directive('child', function($timeout) {
  return {
    restrict: 'E',
    require: '^parent',
    link: function(scope, elem, attrs, parentCtrl) {
      $timeout(function() {
        parentCtrl.setMessage('I am the child!')
      }, 3000)
    }
  }
})

如您所见,该链接接收到带有 parentCtrl 的第四个参数(或者如果有多个参数,则为一个数组)。在这里,我们只需等待 3 秒钟,直到我们调用我们在父控制器中定义的方法来更改其消息。

在这里看到它:http: //plnkr.co/edit/72PjQSOlckGyUQnH7zOA ?p=preview

于 2013-08-29T11:12:48.307 回答
6

首先,观看此视频。它解释了一切。

基本上,你需要require: '^parentDir'然后它将被传递到你的链接函数中:

link: function (scope, element, attrs, ParentCtrl) {
    ParentCtrl.$scope.something = '';
}
于 2013-08-29T02:45:41.450 回答