Lefka
Lefka

Reputation: 673

How do I update the display when a factory is called from a child controller

Let's assume the following HTML:

<div ng-app="myApp" ng-controller="myController">
  {{currentValue}}
  <div ng-controller="myInnerController">
    <button ng-click="toggleValue()">
      Click me
    </button>
  </div>
</div>

And here is the JS:

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

app.controller('myController', ['$scope', 'valueFactory', function($scope, valueFactory) {
    $scope.currentValue = valueFactory.getValue();
  }]);

app.controller('myInnerController', ['$scope', 'valueFactory', function($scope, valueFactory) {
  $scope.toggleValue = function() {
      valueFactory.toggleValue();
    };
}]);

app.factory('valueFactory', function() {
  var value = false;

  var service = {
    getValue: function() {
      return value;
    },
    toggleValue: function() {
      value = !value;
      console.log(value);
    }
  };

  return service;
});

Currently, currentValue will always display false. It should change every time the "click me" button is pressed.

I have tried a few things such as updating $scope.currentValue inside of the inner controller, adding a watch to the parent controller. Nothing I have tried works.

So how do I impact currentValue by calling the factory in the child controller?

FIDDLE

Upvotes: 0

Views: 24

Answers (2)

NodeNewb
NodeNewb

Reputation: 49

I am by far no expert but it looks like you are returning value from the getvalue function without applying the toggle. I think the return needs to be after the toggle function.

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You are assigning boolean type value.

Value type won't keep any bindings.

function,object,array,date are reference type.

This type assignment will keep reference.

Try like this

JS

app.controller('myController', ['$scope', 'valueFactory', function($scope, valueFactory) {
  $scope.valueFactory = valueFactory;

}]);

HTML

{{valueFactory.getValue()}}

JSFIDDLE

Upvotes: 1

Related Questions