Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh a controller from another controller in Angular

Tags:

angularjs

In order to have two controllers speak to each other in Angular, it is recommended to create a common service which is made accessible to both controllers. I've attempted to illustrate this in a very simple fiddle. Depending on which button you press, the app is supposed to tailor the message below the buttons.

So why isn't this working? Am I missing something obvious or more fundamental?

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();
}
like image 838
David Jones Avatar asked Oct 18 '13 08:10

David Jones


2 Answers

Try creating a watch in your controller:

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

Here is a working fiddle http://jsfiddle.net/YFbC2/

like image 52
Yoggi Avatar answered Sep 24 '22 02:09

Yoggi


Seems like problem with property that holds a primitive value. So you can make these changes:

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

See fiddle

like image 29
Peter Gerasimenko Avatar answered Sep 25 '22 02:09

Peter Gerasimenko