简体   繁体   English

在Angular中双向绑定到服务的属性

[英]Two-way binding to property of a service in Angular

I have a service settings that stores some application-wide settings as public variables. 我有一个服务settings ,可以将一些应用程序范围的设置存储为公共变量。 I want to let the user change these settings through various input s. 我想让用户通过各种input更改这些设置。 Therefore, I want to set up a "two-way binding" between a property of the service and an input tag. 因此,我想在服务的属性和input标签之间建立“双向绑定”。

My current approach is to inject the service into a controller: 我当前的方法是将服务注入到控制器中:

.controller('SettingsCtrl', ['settings', '$scope', function (settings, $scope) {

then I attach the settings to the scope: 然后将设置附加到示波器:

  $scope.questionCount = settings.questionCount;

then I write the scope copies back to the service when they change: 然后当它们更改时,我将范围副本写回到服务中:

<input ng-model="questionCount" ng-change="writeBack()">

,

$scope.writeBack = function () {
    settings.questionCount = $scope.questionCount;
};

Am I on the right track here? 我在正确的轨道上吗? What's the best way to achieve this kind of binding? 实现这种绑定的最佳方法是什么?

Well, it depends. 这要看情况。 If you want a full two-way binding you can use a service model that holds all the bindable properties. 如果要进行完整的双向绑定,则可以使用包含所有可绑定属性的服务模型。

For example, on your settings service define a model property like this: 例如,在您的settings服务上,定义一个model属性,如下所示:

this.model = {
  questionCount: 0
}

And on your controller's definition attach the settings.model to the $scope : 然后在控制器的定义上将settings.model附加到$scope

$scope.settingsModel = settings.model;

Then, on the HTML, use it like this: 然后,在HTML上像这样使用它:

<input ng-model="settingsModel.questionCount">

This way you don't need to rely on the ng-change directive, the data is updated directly in the settings service model Object. 这样,您无需依赖ng-change指令,就可以直接在settings服务model Object中更新数据。

The drawback is that, since you are directly binding the data, you need to be careful to (in)validate the input (especially when comes to settings). 缺点是,由于您是直接绑定数据,因此需要小心(无效)输入(特别是在设置时)。 For example, don't allow the user to change manually one of the properties by using a text input box, instead use a list of pre-defined values within a select box. 例如,不允许用户使用文本输入框手动更改属性之一,而应在选择框内使用预定义值的列表。 If you take such precautions you shouldn't have problems with this approach. 如果采取此类预防措施,则此方法应该不会有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM