将param传递给服务函数

时间:2015-09-01 03:35:17

标签: javascript angularjs

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

以上代码演示了如何使用服务在控制器之间进行通信。如果在控制器中更改了值,我只传递true。但是现在如何传递多个param而不是单个true或false?这样我就可以知道哪个控制器的值已经改变了。

0 个答案:

没有答案