gpt4 book ai didi

javascript - Angular 嵌套指令

转载 作者:行者123 更新时间:2023-11-28 07:18:48 27 4
gpt4 key购买 nike

我正在尝试让具有隔离范围的子指令执行一个函数。我似乎无法让具有独立作用域的指令执行其父作用域的函数。这根本行不通。

UsageA:
<div data-outer data-controller="control"><div data-inner></div></div>

Usage B:
<div data-inner data-controller="controlTwo"></div>


app.controller('control', ['$scope', function($scope){
$scope.onOuterChange = function () {
alert("Outer Change");
}
}]);

app.controller('controlTwo', ['$scope', function($scope){
$scope.onInnerChange = function () {
alert("Inner Change");
}
}]);

app.directive('outer', function($compile){
// Runs during compile
return {
scope: {
"onOuterChange": "&",
},
controller: function ($scope, $element) {
},
link: function ($scope, iElm, iAttrs, controller) {
$scope.onInnerChange = function () {
alert("Inner Changed");
}
}
}
});
app.directive('inner', function($compile){
// Runs during compile
return {
scope: {
"onInnerChange": "&",
},
controller: function ($scope, $element) {
},
link: function ($scope, iElm, iAttrs, controller) {
$scope.onInnerChange();
}
}
});

最佳答案

您缺少将 on-outer-change 添加到外部指令,该指令将具有您想要传递给隔离范围指令的函数名称,例如 on-outer-change="onOuterChange( )”。然后,对于内部指令,您应该将该方法传递给 inner 指令隔离范围的 onInnerChange 范围变量。

标记

<div data-outer on-outer-change="onOuterChange()">
<div data-inner on-inner-change="onOuterChange()"></div>
</div>

代码

app.directive('outer', function($compile) {
// Runs during compile
return {
scope: {
"onOuterChange": "&",
},
restrict: 'A',
controller: function($scope, $element) {},
link: function($scope, iElm, iAttrs, controller) {
$scope.onInnerChange = function() {
scope.onOuterChange();
}
}
}
});
app.directive('inner', function($compile) {
// Runs during compile
return {
scope: {
"onInnerChange": "&",
},
controller: function($scope, $element) {},
link: function($scope, iElm, iAttrs, controller) {
$scope.onInnerChange();
}
}
});

Demo here

关于javascript - Angular 嵌套指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30534401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com