当你向自己注入另一个模块时,它实现的控制器和指令变得可用,但你需要正确使用它们。
你正在尝试做的方式是不可能的,你可以做这样的事情: 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
不是建议,但如果你真的需要,你可以用你自己的其他控制器方法,然后复制结果:
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";
};
});
希望帮助
你不引用'SubCtrl'在模板中。所以,不会有'ng-click'方法绑定。 – 2015-03-02 23:01:37
澄清上述评论,其中包括模块不会使所有内容在任何地方自动提供。你所做的只是让控制器可用。所以你仍然需要通过视图或路由将某个控制器包含进去。 – ribsies 2015-03-02 23:06:06
正如我所提到的,subModule是关于一个指令。你是否可以在该指令中强制使用控制器(也许使用配置对象的控制器属性作为我的指令),而不是将指令嵌入到ng-controller中?我只是想知道是否可以使用这个指令更容易在其他应用程序中添加。这个指令是我组织中很多应用程序中的一个通用UI对象。我试图将它变成一个组件,我可以轻松地在任何这些应用程序中添加和使用它。 – 2015-03-03 04:56:48