How to share data between controllers in angularjs

后端 未结 1 1491
感情败类
感情败类 2021-01-07 13:25

I\'m currently trying to learn angularJS and am having trouble accessing data between controllers.

My first controller pulls a list of currencies from my api and ass

相关标签:
1条回答
  • 2021-01-07 13:52

    The most common and recommended method for sharing data between controllers is to use a service. Click here for Live Demo (see app.js)

    var app = angular.module('myApp', []);
    
    app.factory('myService', function() {
      var myService = {
        foo: 'bar'
      };
      return myService;
    });
    
    app.controller('myCtrl1', function(myService) {
      console.log(myService.foo);
      myService.foo = 'not bar anymore!';
    });
    
    app.controller('myCtrl2', function(myService) {
      console.log(myService.foo);
    });
    

    Note: there are several ways of creating a service.

    0 讨论(0)
提交回复
热议问题