Zet Zet - 11 months ago 91
AngularJS Question

Angular factory variable

I'm trying simple Angular app and I have problem

var module = angular.module("app", []);
module.controller('Main', function ($scope, button) {
$scope.displayText = button.dispText;

$scope.increment = function () {
button.increment();
$scope.displayText = button.dispText;
}

})


module.factory('button', function () {
var displayText = '0';
var intButton = 0;

return {
increment: function () {
intButton++;
displayText = intButton.toString()
},
getDisplayText: function () {
return displayText;
},
dispText: intButton.toString()
}
});


Whenever function increment is called variables in my factory get updated, but the value is not transfered to the controller. Why?

Answer Source

You need to call the function getDisplayText() from the factory and assign to the variable

    $scope.increment = function () {
     button.increment();
     $scope.displayText = button.getDisplayText();
   }