[英]Angularjs, how call controller from another controller
I am trying to call a controller within another, to give a name to a particular div. 我试图在另一个内部调用一个控制器,以给特定的div命名。
How to call the controller cook inside the myapp-controll controller? 如何在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>
There are a couple ways, some worse than others: 有几种方法,有些比其他方法差:
You can use scope inheritance by calling up the parent scope from myapp-controller
using $scope.$parent
. 您可以通过使用
$scope.$parent
从myapp-controller
调用父范围来使用范围继承。 This way is very brittle due to the fact that if another scope is introduced in the middle of that chain at some point, your code will break. 这种方法非常脆弱,因为如果在某个时候在该链的中间引入了另一个作用域,则会破坏代码。 This is very possible through things like
ng-repeat
, ng-if
, etc. Plus, Angular 2.0 is doing away with $scope, so if you want to make your code future proof, I would stay away from this approach. 可以通过
ng-repeat
, ng-if
等来实现。此外,Angular 2.0不再使用$ scope,因此,如果您想使代码面向未来,我将不采用这种方法。
You can use event delegation, by using $scope.$emit
to send event information up the scope chain: 您可以使用事件委托,方法是使用
$scope.$emit
在范围链上发送事件信息:
myapp-controller: myapp-controller:
$scope.$emit("eventName", eventData);
app-controller: 应用控制器:
$scope.$on("eventName", callbackFn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.