0

I have 2 controllers i want to call a function in one controller in another. I'm using this and I'm not using any $scope. How can i call a function from one controller to another.

var app = angular.module("myapp", []);

app.controller("myctl", function () {
var parent= this;
 parent.SayHello = function () {
 // code
 }
})
app.controller("otherctl", function () {
 var child = this;
 // how to call sayHello without $scope 
})
asked Feb 13, 2017 at 11:19
3
  • Could you also mention why you are trying to do it this way. Could you not create a factory and inject that both your controllers ? Commented Feb 13, 2017 at 11:21
  • 1
    Are the controllers nested ? Commented Feb 13, 2017 at 11:22
  • You can communicate using events, services (as mentioned) or as @Korte is hinting with $parent if you have a child relationship. It all depends on context which you aren't providing much of. Commented Feb 13, 2017 at 11:43

1 Answer 1

1

You cannot, even if you are using $scope.

You cannot inject one controller to another controller.

In order to share the data among the controllers, consider using factory/service.

DEMO

var app = angular.module("clientApp", [])
 app.controller("TestCtrl", 
 function($scope,names) {
 $scope.names =[];
 $scope.save= function(){
 names.add($scope.name);
 } 
 
 });
 app.controller("TestCtrl2", 
 function($scope,names) {
 $scope.getnames = function(){
 $scope.names = names.get();
 }
});
 
app.factory('names', function(){
 var names = {};
 names.list = [];
 names.add = function(message){
 names.list.push({message});
 }; 
 names.get = function(){
 return names.list;
 };
 return names;
});
<!doctype html>
<html >
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
 <script src="script.js"></script>
</head>
<body ng-app="clientApp">
 <div ng-controller="TestCtrl">
 <input type="text" ng-model="name">
 <button ng-click="save()" > save</button> 
 </div>
 <div ng-init="getnames()" ng-controller="TestCtrl2">
 <div ng-repeat="name in names">
 {{name}}
 </div>
 </div>
</body>
</html>

answered Feb 13, 2017 at 11:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.