Mr.Throg
Mr.Throg

Reputation: 1005

How to call a function from another controller without $scope in Angular JS

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

Upvotes: 0

Views: 885

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

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>

Upvotes: 1

Related Questions