简体   繁体   中英

Angular - Change an object property value in a service and use it in another controller

I am using a service to pass variables between two controllers. But I am struggling how to change the value of an object property. I want to change this value in the first controller and use that new value in the second controller. Below you can find my trial.

The JSfiddle can be found here

HTML code

<div ng-app="myApp">
    <div ng-controller="myController">
        <h3>{{objectValue.data}}</h3>
        <button ng-click="changeObject()">Change the objectValue</button>
    </div>

    <div ng-controller="myController2">
        <h2>{{ newValue.data}}</h2>
    </div>
</div>

JS code

var app = angular.module('myApp', []);

app.service('sharedProperties', function() {
    var objectValue = {
        data: 'default service value'
    };

    return {
        getObject: function() {
            return objectValue;
        }
    }
});


app.controller('myController', function($scope, sharedProperties) {
    $scope.objectValue = sharedProperties.getObject();

    var changeObject = function() {
      sharedProperties.objectValue.data = "New value";
    }
});

app.controller('myController2', function($scope, sharedProperties) {
    $scope.newValue = sharedProperties.getObject();
});

In your first controller in the demo you are assigning only one property from object to a scope variable...making it a primitive. Primitives have no inheritance and are assigned by value

If you maintain reference to same object in each scope model and only display properties of it in view, the binding is maintained through object inheritance.

The primitive used for stringvalue in demo service will never have any inheritance as it is not an object

Using

app.controller('myController1', function($scope, $timeout, sharedProperties) {

    $scope.objectValue = sharedProperties.getObject();    
});

And view

{{objectValue.data}}

Will give you live updates in view due to internal angular watches on the object

DEMO

It is because strings are passed by value and not reference, so changes will not be propagated. Change

<li>{{objectValue}}</li> to <li>{{objectValue.data}}</li>

and

sharedProperties.getObject().data to sharedProperties.getObject() .

And you will see the object bind properly.

If it is your wish to also share strings, consider accessing them from your controllers via getter functions by changing

$scope.stringValue = sharedProperties.getString(); to $scope.getString = sharedProperties.getString;

and

<li>{{stringValue}}</li> to <li>{{getString()}}</li>

See here: http://jsfiddle.net/kbu1ts51/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM