user2422960
user2422960

Reputation: 1526

Binding to service property only via reference?

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?

Upvotes: 5

Views: 92

Answers (2)

Merlin
Merlin

Reputation: 4917

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.

Upvotes: 1

Artem Petrosian
Artem Petrosian

Reputation: 2954

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">

Upvotes: 4

Related Questions