Passing/Updating Data in a Factory from One Controller to Another

若如初见. 提交于 2019-11-30 09:45:46

问题


I'm not sure if I am having a "best practices" issue where I am trying to solve this challenge in a weird and wonderful way or wether my grip on AngularJS just isn't there yet.

Scenario: So I have been trying to come up with a way to have "originCity.cityName" be output on the page a few times, all referencing the same object inside the same factory with the hope that if I set it to some other value ("Test String" for example) then it would retroactively replace all of the {{originCity.cityName}} I have around the page.

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

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

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

In two seperate controllers I have the following call to the factory:

$scope.originCity = cityService.originCity

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

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

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

If I console.log the this.originCity.cityName in the update method inside the factory then it outputs correctly as Test String but the other references to the data do not currently update.


回答1:


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 DOM:

{{originCity.cityName}}


来源:https://stackoverflow.com/questions/30975516/passing-updating-data-in-a-factory-from-one-controller-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!