简体   繁体   English

AngularJS,如何从另一个控制器调用控制器

[英]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: 有几种方法,有些比其他方法差:

  1. You can use scope inheritance by calling up the parent scope from myapp-controller using $scope.$parent . 您可以通过使用$scope.$parentmyapp-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-repeatng-if等来实现。此外,Angular 2.0不再使用$ scope,因此,如果您想使代码面向未来,我将不采用这种方法。

  2. 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);
  1. Use a service / factory to communicate between the two. 使用服务/工厂在两者之间进行通信。 Since they are singletons, you can inject the service / factory into both controllers and then communicate between the controllers using that. 由于它们是单例,因此您可以将服务/工厂注入两个控制器中,然后使用它们在控制器之间进行通信。 This is typically the more widely accepted approach to implementing controller-to-controller communication. 通常,这是实现控制器到控制器通信的更广泛接受的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM