[英]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.