简体   繁体   中英

AngularJS share data between components

Please see this Plunker

There are two components. component1 and common. I want to share data between those two components. In component1.post module, I created a service messages .

// service
angular.module('component1.post').factory('messages', function(sharetexts) {
  const messages = {};

  messages.userInput = sharetexts.userInput;

  messages.changeInput = function(text) {
    sharetexts.change(text);
  };

  return messages;
});

In common.sharedata module

angular.module('common.sharedata', []);

angular.module('common.sharedata').factory('sharetexts', function() {
  const sharetexts = {};

  sharetexts.userInput = 'User Input';

  sharetexts.change = function(text){
    console.log('Service is called.');
    sharetexts.userInput = text;
    console.log(sharetexts);
  }

  return sharetexts;
});

The problem is in the component1.post module, when I input a new text, i can see the userInput changed in common.sharedata . But in module component1.list , {{list.userInput}} does not change.

It is because string is not reference type, but value type. You cannot pass string, because it will be just copied, not referenced.

messages.userInput = sharetexts.userInput; 

Here you just creating new string, not reference to it.

Check this plnkr

https://plnkr.co/edit/rR6MB9QDGCIiYYJ7i1CL?p=preview

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