[英]Angular directive parent and child scope communication
我有一條指令,該指令從指令范圍之外獲取1個變量(zone.id),並使用它來請求一個Promise,然后呈現該指令范圍。
此ID可以來自產品,用戶等。因此,我需要{{zone.id = product.id}}進行分配,以便該指令隨后可以執行某些操作。
稍后,父表單希望在所有請求完成后提交包括指令范圍內的東西在內的整個內容。
我現在正在做的是不隔離范圍,並確保父范圍和子范圍可以通信。 看來,如果我隔離作用域,則父作用域將無法獲得指令作用域內呈現的內容。 (對?..)
angular.module('mean.zone').directive('zonesSelect', ['Zones', function(Zones){
return {
templateUrl: '/zone/views/zonesselectform.html',
restrict : 'E',
scope: false,
controller: function($scope) {
$scope.zone = $scope.zone || {};
$scope.zone.countries = $scope.zone.countries ||[];
$scope.zone.country = $scope.zone.country || {};
$scope.getStates = function(id){
Zones.getsomething(id).then(function(states){
// render the view here....
});
};
},
};
}]);
父表單模板就是這樣。
<div class="form-group">
<div ng-show='false'>
{{zone.id = product.id}}
</div>
<zones-select></zones-select>
</div>
指令模板是這樣的
<select ng-change='getStates(zone.country.id)' data-ng-model='zone.country' data-ng-options="s.name for s in zone.countries" required></select>
這樣就完成了。 只是看起來真的很亂,我想知道是否:
scope:false是實現我想要做的正確選擇嗎?
如果答案是肯定的。 有沒有辦法擺脫屏幕上顯示的變量? {{zone.id = product.id}}
謝謝,任何幫助將不勝感激。
答案1:是的。 如果您不想創建隔離范圍或新范圍,那么scope:false是正確的方法。 但是,如果您要使用zone-select指令,則應考慮創建新的作用域。
答案2:有更好的方法。 如果您想在單個作用域中多次使用指令,那么所做的一切都是不合適的。 因為每次初始化都會刪除您以前的初始化。
以下是更好的方法。
指示
angular.module('mean.zone').directive('zonesSelect', ['Zones', '$parse', function(Zones, $parse){
return {
templateUrl: '/zone/views/zonesselectform.html',
restrict : 'E',
scope: true,
controller: function($scope, attr) {
$scope.zone = $parse(attr.ngModel)($scope) || {};
$scope.zone.countries = $scope.zone.countries ||[];
$scope.zone.country = $scope.zone.country || {};
$scope.getStates = function(id){
Zones.getsomething(id).then(function(states){
// render the view here....
});
};
},
};
}]);
模板
<zones-select ng-model="product"></zones-select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.