1

I have 2 separate controllers (no relation) and one service shared between the two. In controllerA, I have ng-click attribute on an element that is repeated, it is sending a True/False value to a function within the shared service.

When this function receives a call i want to Increment or decrement an integer in ControllerB based on the bit.

ControllerB's Integer should have no dependency on ControllerA, it receives an Count from its own API currently this value is set to the ng-model attribute.

The controllers already share the service. I am unsure how to "Inject" to Controller B, and alter the value of ng-model.

Also is the architecture incorrect ? Since at some point controllers interact should i force a parent child relationship? It is only going to be for a handful of scenarios this will need to happen.

Keith Beard
  • 1,601
  • 4
  • 18
  • 36
  • 3
    Maybe a $broadcast / $emit style of communication between the controllers may suit you. See here for an example: http://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular – Hinrich Aug 26 '15 at 15:26
  • See my answer to a similar question: http://stackoverflow.com/a/32209223/440898 – rtribaldos Aug 26 '15 at 15:29
  • Yet is the ctrlr relationship necessary ? – Keith Beard Aug 26 '15 at 15:30
  • Oh wow they are just getters and setters like in .Net ! How cool is that, lol. When you declare the "Service" in the controler is that an instantiation of the service? – Keith Beard Aug 26 '15 at 15:31

1 Answers1

1

Here's an example from my answer in https://stackoverflow.com/a/32209223/440898

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

angular.module("MyApp")
.service('authenticationSrv', function () {
    var user = {name: 'anonymous'};
    return {
        getUser: function () {
            return user;
        },
        setUserName: function (value) {
            user.name = value;
        }
    };
});

angular.module("MyApp")
.controller("parentCtrl", function ($scope, authenticationSrv) {
    $scope.user = authenticationSrv.getUser();
});

angular.module("MyApp")
.controller("childCtrl", function ($scope, authenticationSrv) {
    authenticationSrv.setUserName('my name');
    $scope.user = authenticationSrv.getUser();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="MyApp">
    <div ng-controller="parentCtrl">
        <p>{{user.name}}</p>
        <div ng-controller="childCtrl">
            <p>{{user.name}}</p>
        </div>
    </div>
</body>
Community
  • 1
  • 1
rtribaldos
  • 1,177
  • 14
  • 28