gpt4 book ai didi

javascript - 我可以将独立作用域和继承作用域结合起来吗?

转载 作者:行者123 更新时间:2023-11-28 00:54:53 25 4
gpt4 key购买 nike

是否可以将独立作用域和继承作用域结合起来?

我有以下结构:

<my-parent-directive>
<my-directive ng-repeat="foo in foos" foo="foo"></my-directive>
</my-parent-directive>


app.module("app").directive("myParentDirective", function(){
return {
//other directive properties
controller: function($scope) {
$scope.myFunc(){//function I want to call from child element
//dostuff
};
},
link: function($scope){
$scope.foos = ["foo", "bar"];
}
};
});

app.module("app").directive("myDirective", function(){
return {
//other directive properties
scope : {foo: "="},
template: "<button ng-click='doStuff()'>doStuff</button>",
controller: function($scope){ //need controller here to do other stuff as well},
link: function($scope){
$scope.doStuff = function() {
//do stuff plus call myFunc
$scope.myFunc();//declared in "parent scope". This does not work
}
}
};
});

所以是的。有办法做到这一点吗?

我使用隔离作用域从父作用域的“foos”数组的 ng-repeat 中获取“foo”。

以前我已经从子元素发出了一个事件并在“父元素”上监听,但我宁愿使用作用域来执行此操作。有什么办法或者我需要使用事件吗?

最佳答案

当然可以!您的内部指令具有独立的作用域,因此看不到其自身之外的任何内容,但您可以使用“&”绑定(bind)将函数传递给您的指令,因此您的指令可能类似于:

<my-directive foo="func()"></my-directive>

我给你做了一把 fiddle here .

关于javascript - 我可以将独立作用域和继承作用域结合起来吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26339228/

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