gpt4 book ai didi

angularjs - 模块之间的 Angular 依赖关系

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

我在模块之间使用依赖注入(inject)时遇到问题。我有一个模块,它实现了我需要在其他应用程序中使用的指令。

我在另一个应用程序声明中添加了该模块的依赖项,如下所示:

angular.module('mainApp', ['ngRoute', 'directiveApp']);

但是,在 MainApp 的页面中似乎看不到实现directiveApp.controller 的方法,因为该指令无法从其 Controller 运行所需的方法。

我知道这有点令人困惑,所以我在这个 plunker 中举了一个例子,这显示了我面临的问题。

最佳答案

当您将另一个模块注入(inject)到自己的模块中时,它实现的 Controller 和指令将变得可用,但您需要正确使用它们。

你尝试做的方式是不可能的,你可以这样做: http://plnkr.co/edit/peHH226vxtkI48RFZ3Eq?p=preview

  <body ng-controller="MainCtrl">
<h1>Value: {{name}}!</h1>
<button ng-click="mainModule()">Call a function in the main module!</button>

<div ng-controller="SubCtrl">
{{name}}
<button ng-click="dependentModule()">Call a function in the dependent module!</button>
</div>
</body>

但请注意,您有两个不同的 $scopes,因此有两个不同的 name 变量。

这意味着您的 dependentModule() 函数属于您的 SubCtrl 并且您只能在其自己的 $scope 内使用它

<小时/>

不建议这样做,但如果您确实需要,您可以在自己的方法上使用其他 Controller ,然后复制结果:

http://plnkr.co/edit/ranK9n08NNVuSKIGX15G?p=preview

main.controller("MainCtrl", function($scope, $controller) {


$scope.name = "Initial value";
$scope.mainModule = function() {
$scope.name = "a function in the same module";
};

$scope.bridgeFunction = function(){
// Create a new scope
var injectedScope = $scope.$new();

// Use it on the other controller
$controller('SubCtrl',{$scope : injectedScope });

// Call the methdo on the controller
testCtrl1ViewModel.dependentModule(); //And call the method on the newScope.

// Copy the result from that scope into your own
$scope.name = testCtrl1ViewModel.name;
}

});
<小时/>

第三个选项是合并两个范围,尽管这可能会变得非常困惑,但这是可能的:

http://plnkr.co/edit/1NKStMuYy0e00dhuWKUD?p=preview

main.controller("MainCtrl", function($scope, $controller) {

$scope.name = "Initial value";

//This can get very messy, but it is possible to merge the two scopes:
$controller('SubCtrl',{$scope : $scope });

$scope.mainModule = function() {
$scope.name = "a function in the same module";
};

});

希望有帮助

关于angularjs - 模块之间的 Angular 依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820944/

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