0

// Code goes here
angular.module('app', [])

.controller('AController', function($scope, aService) {

  $scope.isFinished = false;

  $scope.$watch(function(){return aService.isFinished}, function(newVal, oldVal) {
    $scope.isFinished = newVal;
  });
})

.controller('BController', function($scope, aService, $timeout) {

$scope.load = function(){
    $timeout(function() {
      aService.isFinished = true; // how to pass extra param meter here?
    }, 1000);
}
  
})

.service('aService', function() {
  this.isFinished = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-app="app">
    <div ng-controller="AController">
        is finished? : {{isFinished}}
    </div>
    <div ng-controller="BController">
        <button ng-click="load()">load  of controller B</button>
    </div>
    <div ng-controller="CController">
        <button ng-click="load()">load of controller C</button>
    </div>
  </body>

</html>

Above code demonstrate how I use service to talk between controllers. I just pass true if the value been changed in controllers. But now how to pass multiple param instead of just single true or false? so that I can know from which controller the value been changed.

  • You can pass an object via the service. You can add whatever properties you want to the service to pass state between controllers. – lintmouse Sep 01 '15 at 03:40
  • @dustmouse I thought of object too, would it be better I use factory instead of service in this case? – Siva Natalie Sep 01 '15 at 03:47
  • Eh, it really comes down to preference. For creating a singleton that can share state between controllers, either works. Here's a pretty lengthy discussion about it: http://stackoverflow.com/questions/14324451/angular-service-vs-angular-factory. – lintmouse Sep 01 '15 at 03:51
  • Realised I was solving the problem for a factory, and in essentially the same way as dustmouse described. Sorry about that, I got a little hasty – Roland Heath Sep 01 '15 at 04:06

0 Answers0