我似乎找不到在不使用隔离作用域的情况下从指令中调用父作用域上的函数的方法。我知道如果我使用隔离作用域,我可以只在隔离中使用"&“来访问父作用域上的函数,但是在不必要的时候使用隔离作用域会产生后果。考虑以下HTML:
<button ng-hide="hideButton()" confirm="Are you sure?" confirm-action="doIt()">Do It</button>
在这个简单的例子中,我想要显示一个JavaScript确认对话框,并且只有在确认对话框中单击"OK“时才调用doIt()。使用隔离的作用域很简单。该指令将如下所示:
.directive('confirm', function () {
return {
restrict: 'A',
scope: {
confirm: '@',
confirmAction: '&'
},
link: function (scope, element, attrs) {
element.bind('click', function (e) {
if (confirm(scope.confirm)) {
scope.confirmAction();
}
});
}
};
})
但问题是,因为我使用的是隔离作用域,所以上面示例中的ng-不再针对父作用域执行,而是在隔离作用域中执行(因为在任何指令上使用隔离作用域都会导致该元素上的所有指令都使用该隔离作用域)。在ng- Here is a jsFiddle不起作用的情况下,上述示例的隐藏。(请注意,在此小提琴中,当您在输入框中键入"yes“时,该按钮应隐藏。)
另一种选择是不使用隔离的作用域,这实际上是我在这里真正想要的,因为没有必要隔离此指令的作用域。我唯一的问题是,如果不在隔离作用域上传递方法,我如何在父作用域上调用该方法
其中我没有使用隔离作用域,并且ng- Here is a jsfiddle工作正常,但是,当然,对confirmAction()的调用不起作用,并且我不知道如何使其起作用。
请注意,我真正寻找的答案是如何在不使用隔离作用域的情况下调用外部作用域上的函数。和我对以另一种方式使这个确认对话框工作不感兴趣,因为这个问题的重点是弄清楚如何调用外部作用域,同时仍然能够让其他指令对父作用域起作用。
或者,如果其他指令仍然对父作用域起作用,我会对使用隔离作用域的解决方案感兴趣,但我不认为这是可能的。
发布于 2013-07-12 01:40:56
发布于 2013-07-11 09:52:01
您希望使用AngularJS中的$parse服务。
因此,对于您的示例:
.directive('confirm', function ($parse) {
return {
restrict: 'A',
// Child scope, not isolated
scope : true,
link: function (scope, element, attrs) {
element.bind('click', function (e) {
if (confirm(attrs.confirm)) {
scope.$apply(function(){
// $parse returns a getter function to be
// executed against an object
var fn = $parse(attrs.confirmAction);
// In our case, we want to execute the statement in
// confirmAction i.e. 'doIt()' against the scope
// which this directive is bound to, because the
// scope is a child scope, not an isolated scope.
// The prototypical inheritance of scopes will mean
// that it will eventually find a 'doIt' function
// bound against a parent's scope.
fn(scope, {$event : e});
});
}
});
}
};
});
使用$parse设置属性会遇到一些问题,但当您遇到问题时,我会让您跨过这座桥。
发布于 2013-07-11 08:34:14
在父作用域上显式调用hideButton
。
这就是问题所在:http://jsfiddle.net/pXej2/5/
下面是更新后的HTML:
<div ng-app="myModule" ng-controller="myController">
<input ng-model="showIt"></input>
<button ng-hide="$parent.hideButton()" confirm="Are you sure?" confirm-action="doIt()">Do It</button>
</div>
https://stackoverflow.com/questions/17583004
复制相似问题