[英]How to call AngularJS parent directive scope method from child directive
我有一個帶有確認和取消方法的父模式指令。
ngDialog.open({
scope : true,
showClose : false,
template : theTemplate,
className : 'ngdialog-theme-prompt -small',
controller : ['$scope', function Ctrl($scope) {
$scope.message = message;
$scope.confirm = function(){
$scope.closeThisDialog();
resolve(true);
};
$scope.cancel = function(){
$scope.closeThisDialog();
resolve(false);
};
}]
}).closePromise.then(function () {
resolve(false);
})
模板是另一個指令。
<form class="edit-stakes-content">
<ul>
<li ng-repeat="stake in settings track by $index">
<input type="number" name="input" pattern="^\d+$" min="0" value="{{stake}}" />
</li>
</ul>
<div class="edit-stakes-control">
<button ng-click="cancel();" class="apl-btn apl-btn-link apl-btn-large" translate>CANCEL</button>
<button ng-click="confirm();" autofocus="true" class="apl-btn apl-btn-update apl-btn-large" translate>SAVE</button>
</div>
</form>
在模態的子指令中,我希望能夠執行一些驗證和對服務器的POST,然后調用父模態指令的確認或取消方法。
與此類似:
Directive.$inject = ['UserSettings'];
function Directive(UserSettings) {
function Link($scope) {
$scope.settings = angular.copy(UserSettings.get('presetStakeSettings').settings);
$scope.cancel = $scope.$parent.cancel();
}
return {
'link': Link,
'restrict': 'E',
'replace': true,
'templateUrl': 'betting/edit-stakes/edit-stakes.html'
}
}
調用父方法會引發JavaScript錯誤,即$ scope。$ parent.cancel不是一個函數,似乎可以完成此工作。
有沒有更好的方法來實現子代與父代之間的通信而沒有JavaScript錯誤?
$scope.$parent
通常可以被認為是一種反模式,幾乎沒有很好的用途,通常表明指令設計存在問題或作用域繼承沒有被很好地理解。
Directive
指令不需要新的作用域,因此可以安全地假定它與模式控制器中的作用域相同。 這意味着$scope.$parent
指的是不具有cancel
屬性的模式范圍的父級(可能是根范圍)。
這也意味着$scope.settings
賦值會影響控制器的作用域-顯然不會。 最好在此指令中使用scope: true
繼承scope。
是否有scope: true
無關緊要scope: true
,但是$scope.cancel
將在指令中可用。 它是從模式范圍繼承的。 沒有理由做
$scope.cancel = $scope.$parent.cancel();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.