Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

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

{{originCity.cityName}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...