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>
Similar question has been answered here AngularJS - The correct way of binding to a service properties.
Please read Gil Birman's (Accepted) answer not the Josh David Miller's
I think, even more elegant is to work with promises (see $q.deferred()) and to resolve them asynchronously. In the promise function you can then assign the data to $scope's members.