0

I am trying to call a controller within another, to give a name to a particular div.

How to call the controller cook inside the myapp-controll controller?

<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>

1 Answer 1

2

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. 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.

  2. You can use event delegation, by using $scope.$emit to send event information up the scope chain:

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.
Sign up to request clarification or add additional context in comments.

1 Comment

You can also get the element that the controller is sitting on and calling .$scope(), but #3 is really the widely accepted way to deal with cross controllers communication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.