Transfer / update data in Factory from one controller to another

I'm not sure if I have a "best practices" issue when I try to solve this problem in a weird and wonderful way, or if I can't grab AngularJS, not yet.

Script . So, I was trying to come up with a way to get "originCity.cityName" on the page multiple times by referencing the same object inside the same factory with the hope that if I set it to some other value (for example, "Test String "), it will retroactively replace everything {{originCity.cityName}}

that I have on the page.

module.service('cityFactory', function () {

    return {
        originCity: {
            cityName: 'TestLocation'
        };

        //Update the city
        this.update = function (newCityName) {
            this.originCity.cityName = newCityName;
        }
    });

      

In two separate controllers, I have the following factory call:

$scope.originCity = cityService.originCity

      

And to demonstrate, in a separate controller, I have the following factory update method call:

$scope.setCity = function() {
    cityService.update('Test String');
}

      

As I mentioned above, this is very new to me, so I might be wrong about it all, but I was hoping to have a factory with a method that I can call from anywhere on the page (as long as all dependencies are in the queue) to update this value in multiple places.

If I am console.log

this.originCity.cityName

in an update method inside a factory, then it correctly outputs as Test String

, but other data references are not currently being updated.

+1


source to share


1 answer


module.factory('cityFactory', function () {
    var _cityName = null;
    var cityFactoryInstance = {};

    //Update the city from outside the DOM:
    var _update = function (newCityName) {
        _cityName = newCityName;
    }

    cityFactoryInstance.update = _update;
    cityFactoryInstance.cityName = _cityName;
    return cityFactoryInstance;
});

module.controller('controller1',
    ['$scope','cityFactory', function ($scope, cityFactory) {

        $scope.originCity.cityName = cityFactory.cityName;
    }]);

module.controller('controller2',
    ['$scope', 'cityFactory', function ($scope, cityFactory) {

        $scope.originCity.cityName = cityFactory.cityName;
    }]);

      

In the DOM:



{{originCity.cityName}}

      

0


source







All Articles