Consider a service:
app.service('myService',function(){
this.strProp = '';
this.objProp = {
content: ''
}
})
And a controller:
app.controller('myCtrl',function($scope,myService){
$scope.str = myService.strProp;
$scope.obj = myService.objProp;
})
Also consider a markup that binds both scope properties
<input type="text" ng-model="str">
<input type="text" ng-model="obj.content">
When those values get updated through the view via user input, my service will show only those changes made to the object, while the string property stays empty.
Am I right in assuming that this is caused by the fact that the object is bound via reference and the string is not?
Binding to a propertylink To bind to an element's property, enclose it in square brackets, [] , which identifies the property as a target property. A target property is the DOM property to which you want to assign a value.
In Angular 7, property binding is used to pass data from the component class (component. ts) and setting the value of the given element in the user-end (component. html). Property binding is an example of one-way databinding where the data is transferred from the component to the class.
Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code. Actually, Angular internally converts string interpolation into property binding.
It involves updating the value of a property in the component and binding it to an element in the view template. Property binding uses the [] syntax for data binding.
Thats right, in your example strProp
is bound by value.
When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.
Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function.
So, probably you have to change you code like this:
$scope.someProp = myService;
And then pass it into your view:
<input type="text" ng-model="someProp.strProp">
<input type="text" ng-model="someProp.objProp.content">
According to the O'REILLY Angularjs
book we should always use Object
instead of primitives
to contain your data.
Though this
primitive-style model
works in simple cases, for most applications you’ll want to create a model object to contain your data creating a model object will prevent unexpected behavior that could be caused by the prototypal inheritance in$scope objects
.
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