gpt4 book ai didi

javascript - AngularJS:包含相同的 Controller

转载 作者:行者123 更新时间:2023-11-29 15:34:21 24 4
gpt4 key购买 nike

我有一个像这样包装另一个指令的指令:

<div direction from="origin" to="destination">
<div direction-map line-color="#e84c3d"></div>
</div>

direction-map 指令被嵌入,参见我的代码(Fiddle available here):

var directionController = function() {
//do stuffs
};
var directionMapController = function() {
//do other stuffs
};
var Direction = angular.module("direction", [])
.controller("directionController", directionController)
.controller("directionMapController", directionMapController)
.directive("direction", function() {
var directive = {
restrict: "AEC",
controller: "directionController",
scope: {},
transclude: true,
link: {
pre: function($scope, $element, attrs, controller, transclude) {
console.log("direction's controller is directionController : ");
console.log(controller.constructor === directionController);//true, that's ok
transclude($scope, function(clone) {
$element.append(clone);
});
}
}
};
return directive;
})
.directive("directionMap", function() {
var directive = {
require: "^direction",
controller: "directionMapController",
restrict: "AEC",
scope: true,
link: {
pre: function($scope, $element, $attrs, controller) {
console.log("directionMap's controller is directionMapController :");
console.log(controller.constructor===directionMapController);//false that's not OK!!!!
}
}
};
return directive;
});

所以我的问题是:

为什么我的子指令 direction-map 获取其父级 Controller 的参数(我认为这是因为它被嵌入),是否有可能避免这种情况或者我应该重新考虑我的代码?

最佳答案

发生这种情况是因为您正在使用 require: "^direction" 如果您删除此行,指令将获得自身的 Controller 而不是父 Controller 。

希望对你有帮助:)

已更新 Fiddle

关于javascript - AngularJS:包含相同的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31137152/

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