2013-08-29 131 views
12

我不知道这是要做到这一点的方式,但我的目标是:Angularjs:与孩子的指令集父指令范围值

  • 我有一个父指令
  • 父里面指令的块,我有一个孩子的指令,将获得来自用户
  • 儿童指令将设置父指令的范围值,一些输入
  • 我可以把它从那里

当然问题是父母和孩子的指令是兄弟姐妹。所以我不知道该怎么做。注 - 我不想在

小提琴组数据: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 
     } 
    }; 
}); 
+0

布赖恩视频和耶稣的plunker是完美的。我加了一个编辑小提琴 - 使用$ watch不断更新父指令的范围(否则它只发生在耶稣的掠夺者身上)。 http://jsfiddle.net/rrosen326/7Dq4e/ –

回答

26

如果你想要那个类型的通信,需要在孩子directive使用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

首先,看this video。它解释了一切。

基本上,你需要require: '^parentDir',然后它会被传递给你的链接功能:

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