[英]Pass variables to a dynamic Controller inside a Directive AngularJS
我得到了一個指令,該指令根據傳遞給它的變量類型 加載不同的模板 。 我也將變量耐心和服務傳遞給指令的隔離范圍。
.directive('serviceCharts', serviceCharts);
function serviceCharts() {
return {
restrict: 'E',
link: function (scope, element, attrs) {
if(attrs.type) {
scope.template = 'views/' + type + '.html';
}
attrs.$observe('type', function (type) {
if(attrs.type) {
scope.template = 'views/' + type + '.html';
}
});
},
template: '<div ng-include="template"></div>',
scope:{
patient:'=',
service:'='
}
};
}
在模板中 (例如,views / myservice.html),我加載了控制器 :
<div ng-controller="myCtrl as vm">
VIEW
</div>
在控制器(myCtrl)中,我以這種方式訪問 患者並進行服務 :
service = $scope.$parent.$parent.service;
patient = $scope.$parent.$parent.patient;
這工作正常,但我不喜歡這種通過$ parent。$ parent訪問變量的方式。 這也弄亂了我的測試。
還有另一種(更好)的方法嗎?
謝謝!
您可以為patient
和service
屬性創建包裝對象。 可以將其命名為model
,然后將該模型對象提供給您的指令。
然后,當前方法的問題是, ng-include
為其創建template
的子范圍。 因此,如將傳遞的原始類型對象綁定到指令一樣,如果要在子作用域中更改任何子原始類型綁定。 它失去了綁定,這就是為什么傾向於使用$parent.$parent
符號完全綁定到原始源對象的原因。
$scope.model = {
patient:'My Patient',
service:'My Service'
};
通過創建上述對象結構,可以確保您遵循Dot Rule
。 Dot Rule
將避免$parent.$parent
顯式范圍注釋。
指令范圍綁定將更改為以下
scope:{
model:'='
}
指令用法如下所示
<service-charts type="{{'sometype'}}" model="model"></service-charts>
除了點規則以外,針對這種范圍界定問題的另一種選擇是遵循controllerAs
模式。 但是接下來,您bindToController: true
controllerAs
使用隔離scope
,因此應將bindToController: true
選項設置為true,以確保將所有scope
合並到控制器上下文中。
scope:{
patient:'=',
service:'='
},
controllerAs: '$ctrl',
bindToController: true
然后在每個指令作用域變量之前使用$ctrl
。
是的,有更好的方法可以做到這一點。 您應該使用services
並將變量存儲在這些服務中(在這種情況下,您應該創建一個工廠來存儲數據)。 然后,您可以注入這些服務並訪問其數據。
旁注:您可以在指令中使用{ ..., controller: 'controllerName', controllerAs: 'vm' }
語法,因此您無需在html中聲明它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.