我不确定我是否有一个“最佳实践”问题,我试图以一种奇怪而奇妙的方式解决这个挑战,或者我对AngularJS的控制还没有.
场景:所以我一直试图找到一种方法让“originCity.cityName”在页面上输出几次,所有引用同一工厂内的相同对象,希望如果我将它设置为其他值(例如“测试字符串”)然后它将追溯替换页面周围的所有{{originCity.cityName}}.
module.service('cityFactory',function () { return { originCity: { cityName: 'TestLocation' }; //Update the city this.update = function (newCityName) { this.originCity.cityName = newCityName; } });
在两个单独的控制器中,我有以下工厂的电话:
$scope.originCity = cityService.originCity
并且,为了演示,在一个单独的控制器中,我有以下调用工厂的更新方法:
$scope.setCity = function() { cityService.update('Test String'); }
正如我上面提到的,这对我来说是非常新的,所以我可能会发现这一切都错了,但我希望有一个工厂,我可以从页面的任何地方调用一个方法(只要依赖项全部在line)在几个地方更新该值.
如果我在工厂内的update方法中调用this.originCity.cityName,那么它将作为测试字符串正确输出,但其他对数据的引用当前不会更新.
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',cityFactory) { $scope.originCity.cityName = cityFactory.cityName; }]);
在DOM中:
{{originCity.cityName}}