[英]How to pass data from parent to child controller using angular $broadcast?
[英]In angular js, How do I pass data from a parent controller to a child controller?
我有一個小小部件,我想在一個頁面上反復使用。 它有自己的控制器。 問題是它需要一個數據來操作(基本上是一個鍵),每個鍵都包含在父控制器中。
這是一個例子(顯然是錯誤的)
http://plnkr.co/edit/VajgOr1LqpLDnbEJcvor?p=preview
腳本:
angular.module('myApp', [])
.controller('ParentCtrl', ['$scope',
function($scope) {
$scope.keyForChartABC = "somekey1";
$scope.keyForChartXYZ = "somekey2";
$scope.keyForChartLALA = "somekey3";
}
])
.controller('ChartCtrl', ['$scope',
function($scope) {
//todo: have $scope.key assigned from parent somehow
//not shown: use $scope.key to pull data and format chart data
}
])
指數:
<!-- ng-init like this is quite wrong -->
<div ng-init="key = keyForChartABC"
ng-include="'chartwidget.html'"></div>
<hr>
<div ng-init="key = keyForChartXYZ"
ng-include="'chartwidget.html'"></div>
<hr>
<div ng-init="key = keyForChartLALA"
ng-include="'chartwidget.html'"></div>
chartwidget:
<div ng-controller="ChartCtrl">
<p>Drawing chart for data: {{key}}</p>
<p>some chart directive here</p>
</div>
正如你在plunker中看到的那樣,我在這里用ng-init嘗試的東西不起作用 - 所有子控制器的鍵最終都具有相同的值。
我已經使用ng-repeat和父數據庫中的一組數據,不知何故$ index將每個子項設置為正確的索引並保留一個值。 但是我想在這種情況下避免使用ng-repeat,這樣我就可以更好地控制布局了。
創建可重用的小部件正是指令的目的。 您可以創建一個指令來輕松處理窗口小部件的輸出。
我分叉你的plunker並修改它以改變它以使用指令。
以下是一些亮點:
首先,您的模板不再需要在其中定義的控制器。
<div>
<p>Drawing chart for data: {{key}}</p>
<p>some chart directive here</p>
</div>
接下來,定義了一個指令,它具有一個隔離范圍,該范圍對於該指令的每個實例都是唯一的:
.directive('chartWidget', function(){
return {
restrict: 'E',
scope: {
key: '='
},
templateUrl : 'chartwidget.html'
}
})
最后,該指令在HTML中聲明。 請注意JavaScript中指令的camel-case名稱,但HTML中帶有連字符的名稱:
<div>
<chart-widget key="keyForChartABC"></chart-widget>
<hr>
<chart-widget key="keyForChartXYZ"></chart-widget>
<hr>
<chart-widget key="keyForChartLALA"></chart-widget>
</div>
編輯
我更新了plunker以顯示將指令屬性綁定到內部控制器。 此方法使用ControllerAs語法定義控制器,並將指令的作用域綁定到控制器作用域。
相關變化:
.directive('chartWidget', function(){
return {
restrict: 'E',
scope: {
key: '='
},
templateUrl : 'chartwidget.html',
controller: 'chartWidgetController',
controllerAs: 'ctrl',
bindToController: true
}
})
.controller('chartWidgetController', function(){
console.log(this.key);
})
對模板進行一些小改動以支持ControllerAs:
<div>
<p>Drawing chart for data: {{ctrl.key}}</p>
<p>some chart directive here</p>
</div>
請注意,嘗試在模板中使用ng-controller=
將導致模板與為指令創建的范圍對象具有不同的范圍對象,並且控制器將無法訪問指令上定義的屬性。
另請注意, bindToController
是角度1.3.x或更高的功能。 在角度1.2.x或更早版本中,您唯一的選擇是使用$scope.$watch
來監視隔離范圍的變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.