在 AngularJS 服务中处理数据绑定 [英] Handling data binding in AngularJS Services
问题描述
我想弄清楚当我的数据存储在服务中时您如何正确处理绑定.
如果将服务放入 $scope 中,然后让模板直接绑定到它,我可以让事情正常工作,但这似乎是一个非常糟糕的主意.
我基本上希望拥有它,以便我的视图/控制器能够轻松地更改服务中的状态并将其反映到任何地方.
感觉我应该能够做类似以下的事情,但它不起作用(http://jsfiddle.net/aidankane/AtRVD/1/).
HTML
<select ng-model="drawing" ng-options="d.file for d in graphics"></select><div ng-controller="MyOtherCtl">{{ 画画 }}
JS
var myApp = angular.module('myApp', []);myApp.factory('myService', function(){变量我 = {图纸:[{'file':'a'}, {'file':'b'}]};//选中的图me.drawing = me.drawings[0];还我;});函数 MyCtl($scope, myService){//可以做://$scope.mys = myService;//然后在 html ng-model="mys.drawing"//但这似乎是错误的$scope.drawings = myService.drawings;$scope.drawing = myService.drawing;//我可以不这样做吗?无论如何它似乎不起作用......$scope.$watch('绘图', 函数(绘图){myService.drawing = 绘图;});}函数 MyOtherCtl($scope, myService){$scope.drawing = myService.drawing;}MyCtl.$inject = ['$scope', 'myService'];MyOtherCtl.$inject = ['$scope', 'myService'];
您可以使用 $watch
绑定到服务并传递一个函数:
$scope.$watch( function () { return myService.drawing; }, function (drawing ) {//在这里处理.例如.:$scope.drawing = 绘图;});
然后在你的模板中使用 $scope.drawing
,它们会自动更新:
{{ 画画 }}
I'm trying to figure out how you handle binding properly when my data is stored in a service.
I can get things working if it put the service into the $scope and then get the templates to bind directly into it but that seems like a really bad idea.
I'd basically like to have it so that my views / controllers are able to easily change the state down in a service and have that reflected everywhere.
It feels like I should be able to do something like the following, but it doesn't work (http://jsfiddle.net/aidankane/AtRVD/1/).
HTML
<div ng-controller="MyCtl">
<select ng-model="drawing" ng-options="d.file for d in drawings"></select>
</div>
<div ng-controller="MyOtherCtl">
{{ drawing }}
</div>
JS
var myApp = angular.module('myApp', []);
myApp.factory('myService', function(){
var me = {
drawings: [{'file':'a'}, {'file':'b'}]
};
// selected drawing
me.drawing = me.drawings[0];
return me;
});
function MyCtl($scope, myService){
// can do:
// $scope.mys = myService;
// and then in html ng-model="mys.drawing"
// but that seems wrong
$scope.drawings = myService.drawings;
$scope.drawing = myService.drawing;
// can I not do this? it doesn't seem to work anyway...
$scope.$watch('drawing', function(drawing){
myService.drawing = drawing;
});
}
function MyOtherCtl($scope, myService){
$scope.drawing = myService.drawing;
}
MyCtl.$inject = ['$scope', 'myService'];
MyOtherCtl.$inject = ['$scope', 'myService'];
You can bind to services using $watch
and passing a function:
$scope.$watch( function () { return myService.drawing; }, function ( drawing ) {
// handle it here. e.g.:
$scope.drawing = drawing;
});
And then use $scope.drawing
in your templates and they will automatically update:
<div ng-controller="MyOtherCtl">
{{ drawing }}
</div>
这篇关于在 AngularJS 服务中处理数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!