我试图弄清楚当我的数据存储在服务中时如何正确处理绑定。
如果将服务放入 $scope 然后让模板直接绑定到其中,我可以让事情正常工作,但这似乎是一个非常糟糕的主意。
我基本上希望拥有它,以便我的视图/控制器能够轻松地更改服务中的状态并将其反映在任何地方。
感觉我应该能够执行以下操作,但它不起作用(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'];