gpt4 book ai didi

javascript - 在 Angular 指令中访问父 Controller

转载 作者:行者123 更新时间:2023-11-28 01:02:09 25 4
gpt4 key购买 nike

我有一个指令可以动态设置给定应用程序状态的标题栏内容。

我希望能够访问当前 View 的 Controller 中的函数和变量,但我只能访问我的 RootCtrl

该指令如下所示。

return {
restrict: 'EA',
template: "<div ng-include='getState()'></div>",
transclude: true,
scope: false,
controller: ['$scope', '$state', function($scope, $state) {
//some logic to retrieve and return the correct header template html
}],
link: function(scope, element, attrs){
console.log(scope.test);
console.log(scope.test2);
}
}

还有 Controller 。

.controller('RootCtrl', function($scope, $state, $location, $rootScope) {
$scope.test = 'hello';
//...
})

.controller('ContactsCtrl', function($scope, $state, CustomerService) {
console.log('Contacts init');
$scope.test2 = 'hello 2';
//...
})

当我导航到联系人状态时,输出如下所示。

hello
undefined
Contacts init

如果我希望能够访问 test2 变量,我该怎么办?

最佳答案

您需要在指令中使用 require 属性。这将使定义的 Controller 的范围在链接函数中作为第四个参数可用。然后,您可以在链接函数内以数组形式访问范围。

您的代码可能如下所示:

return {
restrict: 'EA',
template: "<div ng-include='getState()'></div>",
transclude: true,
scope: false,
require:['^RootCtrl', '^ContactsCtrl'],
controller: ['$scope', '$state', function($scope, $state) {
//some logic to retrieve and return the correct header template html
}],
link: function(scope, element, attrs, requiredControllers){
console.log(requiredControllers[0].test);
console.log(requiredControllers[1].test2);
}
}

请参阅 Directives 的 Angular 文档有关更多示例(在标题创建通信指令下)以及 ^controller 语法的说明。

关于javascript - 在 Angular 指令中访问父 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25490438/

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