Reputation: 673
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?
Upvotes: 0
Views: 24
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
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()}}
Upvotes: 1