从Angular中的另一个控制器刷新控制器

时间:2013-10-18 08:31:15

标签: angularjs

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

那么为什么这不起作用?我错过了一些明显或更基本的东西吗?

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

3 个答案:

答案 0 :(得分:17)

尝试在控制器中创建手表:

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

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

答案 1 :(得分:5)

似乎与property that holds a primitive value的问题相似。所以你可以做出这些改变:

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

请参阅fiddle

答案 2 :(得分:3)

只需拨打HTML Service.getNumber()和控制器ControllerTwo,即可拨打服务:

 $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