![](/img/trans.png)
[英]Angularjs how to call a function of a controller from another controller
[英]Angularjs, how call controller from another controller
我试图在另一个内部调用一个控制器,以给特定的div命名。
如何在myapp-controll控制器中调用控制器Cook ?
<html ng-app="myapp">
<body ng-controller="myapp-controll">
<ng-view></ng-view>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.2/angular.min.js"></script>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.config(function($routeProvider) {
$routeProvider
.when('/:acess', {
templateUrl : 'sources/default.html',
controller : 'myapp-controll'
})
});
myapp.controller('myapp-controll', function($scope, $routeParams) {
$scope.templateUrl = 'sources/'+$routeParams.acess+'.html';
});
myapp.controller('cook', function($scope, $routeParams) {
$scope.pagetitle = 'cook';
});
</script>
</body>
</html>
有几种方法,有些比其他方法差:
您可以通过使用$scope.$parent
从myapp-controller
调用父范围来使用范围继承。 这种方法非常脆弱,因为如果在某个时候在该链的中间引入了另一个作用域,则会破坏代码。 可以通过ng-repeat
, ng-if
等来实现。此外,Angular 2.0不再使用$ scope,因此,如果您想使代码面向未来,我将不采用这种方法。
您可以使用事件委托,方法是使用$scope.$emit
在范围链上发送事件信息:
myapp-controller:
$scope.$emit("eventName", eventData);
应用控制器:
$scope.$on("eventName", callbackFn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.