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'];
AngularJs support one-way binding as well as two-way binding. Most templating systems work with one-way databinding. They merge the model component and template together into a view. When the merge occurrs, the model data is bound to the view.
AngularJS creates a two way data-binding between the select element and the $ctrl. orderProp model. $ctrl. orderProp is then used as the input for the orderBy filter.
The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.
As mentioned earlier, one-way data binding in Angular can be of three types i.e Interpolation, Property binding, and Event binding.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With