我听说过,该服务不应该链接到控制器中的作用域变量,因为视图获得了对服务的直接访问。但是,我希望将我的作用域变量绑定到存储在服务中的数据,并且希望该变量能够反映来自服务的所有更改。我已经阅读了很多解决方法,如果我想从控制器中查看服务数据,那么大多数人都会被告知使用$scope.$watch。我编写了简单的示例,没有使用$scope.$watch,它的工作方式与我想要的完全一样,但我肯定不能肯定,我是否可以使用这样的东西,或者这是一个糟糕的实践。我大约学了2-3天,非常需要你的建议:
html:
<div ng-controller="TestController">
<p>Current value = {{ serviceData.getValue() }}</p>
<input type="text" ng-model="newValue">
<button ng-click="changeServiceData(newValue)">Change</button>
</div>module.js
var app = angular.module('app', []);controller.js
app.controller('TestController', function($scope, testService){
$scope.serviceData = testService.getPublicData();
$scope.changeServiceData = function(newValue){
testService.setValue(newValue);
}
});service.js
app.factory('testService', function(){
var value = null;
return {
setValue: function(newValue){
value = newValue;
},
getPublicData: function(){
return {
getValue: function(){
return value;
}
}
}
}
});总之,视图只能访问getter。要更新数据,我使用的是服务,我可以将服务注入到任何控制器中,并且服务中的所有更改都反映在控制器和视图中。
更新:我试图像这样改变我的工厂:
app.factory('testService', function(){
var value = null;
return {
setValue: function(newValue){
value = newValue;
},
getValue: function(){
return value;
}
}});
并将getter分配到范围:
app.controller('TestController', function($scope, testService){
$scope.value = testService.getValue();
$scope.changeServiceData = function(newValue){
testService.setValue(newValue);
}
});在这种情况下,如果我使用setter从视图中更改服务中的值,则值不会在视图中隐含地变化,它不会反映实际的服务数据。也许你能解释一下这种行为?
发布于 2015-11-25 19:53:25
您的更新几乎是正确的,如果您已经决定使用包含变量的服务,那么它将是共享的模块和控制器。
现在只需要使用这个getter和setter:
app.controller('TestController', function($scope, testService){
$scope.testService = testService;
$scope.newValue = 'initial-value';
});在HTML中:
<div ng-controller="TestController">
<p>Current value = {{ testService.getValue() }}</p>
<input type="text" ng-model="newValue">
<button ng-click="testService.setValue(newValue)">Change</button>
</div>现在,我们仍然将值放入范围,因为很明显,您只想在单击时更新服务值,因此需要从服务本身去同步它。
如果要将服务值直接绑定到该输入的ngModel,则不能使用getter,但必须直接使用变量:
<input ng-model="testService.value">或者最后一个选项是使用newValue指令传播对ngChange所做的任何更改:
<input ng-model="newValue" ng-change="testService.setValue(newValue)">https://stackoverflow.com/questions/33904608
复制相似问题