将工厂中的数据从一个控制器传递

将工厂中的数据从一个控制器传递

本文介绍了将工厂中的数据从一个控制器传递/更新到另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否遇到了最佳实践"问题,我试图以一种奇怪而美妙的方式解决这个挑战,或者我对 AngularJS 的掌握还没有.

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.

场景:所以我一直试图想出一种方法让originCity.cityName"在页面上输出几次,所有这些都引用同一个工厂内的同一个对象希望如果我将它设置为其他值(例如测试字符串"),那么它会追溯替换我在页面周围的所有 {{originCity.cityName}}.

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.

如果我 console.log 工厂内部更新方法中的 this.originCity.cityName 那么它会正确输出为 Test String 但是对数据的其他引用当前未更新.

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.

推荐答案

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;
    }]);

在 DOM 中:

{{originCity.cityName}}

这篇关于将工厂中的数据从一个控制器传递/更新到另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:35