Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...