且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJs:在控制器之间的数据共享

更新时间:2023-11-17 12:05:04

有一个解决方案,但它需要一些额外的配置,而使得航线的 $ routeProvider ,你可以解决你的路线,当你有从后端数据获取。如果由用户刷新你的项目的一个页面中使用了这种方法,它会先接收数据然后显示特定页面。

There is a solution but it needs some additional configuration while making routes in your $routeProvider, You can resolve your route when you have your data fetch from the backend. By using this method if a user refreshes the page on one of your project it will receive the data first then display that particular page.

首先,你必须修改的DataFactory 像这样

First you have to modify your dataFactory something like this

app.service('MyService', function($http) {
    var myData = null;

    var promise = promise || $http.get('data.json').success(function (data) {
      myData = data;
    });

    return {
      promise:promise,
      doStuff: function () {
          return myData
      }
    };
});

然后在你的 $ routeProvider 你可以把路由来解决,当你的数据被取出(即接收其承诺),更在用这种方法,它不会让另一个数据打电话,如果你的数据存储。

Then in your $routeProvider you could make route to resolve when your data is fetched (that is receives its promise) more over by using this method it wont make another data call if your data is stored.

app.config(function($routeProvider){
  $routeProvider
    .when('/',{controller:'MainCtrl',
    template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        return MyService.promise;
      }
    }})
    .when('/b',{controller:'MainCtrl2',
    template:'<div>From MyServic2e:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        return MyService.promise;
      }
    }})
  })

我已经为一个演示做了工作 Plunker 。下跌免费问对此的任何问题。

I've a made a working Plunker for demo. Fell free to ask any question regarding this.

希望它帮助。