AngularJS:如何使用子指令设置父指令的作用域值

12

我不确定这是否是正确的方法,但我的目标是:

  • 我有一个父指令
  • 在父指令块内,我有一个子指令会获取用户输入
  • 子指令将在父指令范围内设置一个值
  • 从那里我可以继续处理

当然问题在于父指令和子指令是兄弟关系。所以我不知道该怎么做。注意 - 我不想在

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

Brian的视频和Jesus的plunker都非常完美。我对我的fiddle进行了编辑,增加了一个$watch来持续更新父指令的作用域(否则只会在Jesus的plunker中发生一次)。http://jsfiddle.net/rrosen326/7Dq4e/ - Ross R
2个回答

27
如果您想要这种类型的通信,您需要在子指令中使用require。这将需要父级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


6

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

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

link: function (scope, element, attrs, ParentCtrl) {
    ParentCtrl.$scope.something = '';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接