gpt4 book ai didi

angularjs - Angular 需要父 Controller 而不明确指定名称

转载 作者:行者123 更新时间:2023-12-02 01:31:54 24 4
gpt4 key购买 nike

此处显示的子指令中需要父 Controller 的常见场景:

Client 指令需要父Server Controller

  <div server>
<div client></div>
</div>



var app = angular.module("app", []);

app.directive("server", function() {
return {
controller: function() {
this.log = function(message) {
console.log(message);
};
}
};
});

app.directive("client", function() {
return {
require: "^server",
link: function($scope, $elem, $attrs, serverCtrl) {
serverCtrl.log("Hello, this is the client!");
}
};
});

如果我有一个名为 MegaServer 的第三个指令指令怎么办?

app.directive("MegaServer", function() {
return {
controller: function() {
this.log = function(message) {
console.log(message);
};
}
};
});

MegaServer 也可以是“Client”的父级。

  <div server>
<div client></div>
</div>
<div mega-server>
<div client></div>
</div>

如果父 Controller 可以是 ServerMegaServer 类型,我该如何定义我的 Client 指令来要求父 Controller ?

最佳答案

让其他服务器在其 $scope 上发布其 this。然后让 client 指令使用可选的必需 serverCtrl$scope.serverCtrl

angular.module("app").directive("otherServer", function() {
return {
controller: function($scope) {
$scope.serverCtrl = this;
this.log = function(message) {
console.log("otherServer: ", message);
};
}
};
});

angular.module("app").directive("client", function() {
return {
require: "^?server",
link: function(scope, elem, attrs, serverCtrl) {
var ctrl = serverCtrl || scope.serverCtrl;
if (ctrl) {
ctrl.log("Hello, from a client");
ctrl.log("My scope.$id is " + scope.$id);
};
}
};
});

试一试 on JSFiddle .

关于angularjs - Angular 需要父 Controller 而不明确指定名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720946/

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