13

为了让两个控制器在 Angular 中相互通信,建议创建一个公共服务,让两个控制器都可以访问。我试图用一个非常简单的小提琴来说明这一点。根据您按下的按钮,该应用程序应该定制按钮下方的消息。

那么为什么这不起作用呢?我是否遗漏了一些明显或更基本的东西?

HTML

<div ng-controller="ControllerOne">
  <button ng-click="setNumber(1)">One</button>
  <button ng-click="setNumber(2)">Two</button>
</div>
<div ng-controller="ControllerTwo">{{number}} was chosen!</div>

JavaScript

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

app.factory("Service", function () {
  var number = 1;
  function getNumber() {
    return number;
  }
  function setNumber(newNumber) {
    number = newNumber;
  }
  return {
    getNumber: getNumber,
    setNumber: setNumber,
  }
});

function ControllerOne($scope, Service) {
  $scope.setNumber = Service.setNumber;
}

function ControllerTwo($scope, Service) {
  $scope.number = Service.getNumber();
}
4

3 回答 3

17

尝试在您的控制器中创建一个手表:

$scope.$watch(function () { return Service.getNumber(); },
   function (value) {
       $scope.number = value;
   }
);

这是一个工作小提琴http://jsfiddle.net/YFbC2/

于 2013-10-18T08:39:41.827 回答
5

似乎是拥有原始值的属性的问题。因此,您可以进行以下更改:

app.factory("Service", function () {
    var number = {val: 1};
     function getNumber() {
        return number;
    }
    function setNumber(newNumber) {
        number.val = newNumber;
    }
    return {
        getNumber: getNumber,
        setNumber: setNumber,
    }
});

小提琴

于 2013-10-18T08:40:30.007 回答
3

只需调用 HTMLService.getNumber()和控制器ControllerTwo调用 Service,如:

 $scope.Service = Service;

例子:

HTML

<div ng-controller="ControllerOne">
  <button ng-click="setNumber(1)">One</button>
  <button ng-click="setNumber(2)">Two</button>
</div>
<div ng-controller="ControllerTwo">{{Service.getNumber()}} was chosen!</div>  

JS

function ControllerOne($scope, Service) {    
    $scope.setNumber = Service.setNumber;  
}

function ControllerTwo($scope, Service) {
        $scope.Service = Service;
}

演示Fidlle

于 2013-10-18T09:16:20.510 回答