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
$watchand passing a function:And then use
$scope.drawingin your templates and they will automatically update: