繁体   English   中英

AngularJS在组件之间共享数据

[英]AngularJS share data between components

请参阅此柱塞

有两个部分。 component1和common。 我想在这两个组件之间共享数据。 component1.post模块中,我创建了一个服务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;
});

common.sharedata模块中

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;
});

问题出在component1.post模块中,当我输入新文本时,我可以看到userInput中的userInput发生了common.sharedata 但是在模块component1.list{{list.userInput}}不会更改。

这是因为字符串不是引用类型,而是值类型。 您不能传递字符串,因为它将仅被复制而不被引用。

messages.userInput = sharetexts.userInput; 

在这里,您只是创建新的字符串,而不是对其进行引用。

检查这个plnkr

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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