简体   繁体   English

从AngularJS控制器获取数据

[英]Fetch data from AngularJS controller

I'm migrating jquery code to AngularJs. 我正在将jquery代码迁移到AngularJs。

My existing code grabs a list of names from an ajax call, which are then exposed via a get function which returns a list. 我现有的代码从ajax调用中获取一个名称列表,然后通过返回列表的get函数公开。 This list sits in an object called "dataBrowser". 此列表位于名为“dataBrowser”的对象中。

So basically in my existing code I can do: 所以基本上在我现有的代码中我可以做到:

$.each(this.dataBrowser.getList(), function(key, item)
{
    // print table row to html
});

Now I want to display that list in a table using ng-repeat. 现在我想使用ng-repeat在表格中显示该列表。

My question is, how do I best access dataBrowser.getList() from the controller? 我的问题是,如何从控制器中最好地访问dataBrowser.getList()?

I have a global "application", so I could just grab it via application.dataBrowser.getList(), but I don't like using a global. 我有一个全局“应用程序”,所以我可以通过application.dataBrowser.getList()获取它,但我不喜欢使用全局。 Should I pass dataBrowser as an object into the controller when I create it? 在创建数据时,我应该将dataBrowser作为对象传递给控制器​​吗?

What's the best approach? 什么是最好的方法?

The best approach would be to put that ajax call in a service that uses $http and access the data from the service. 最好的方法是将ajax调用放在使用$ http并访问服务数据的服务中。 So something like 所以像

var app = angular.module('app');
app.factory('DataBrowser' /*or whatever*/, function($http) {
  var data = {};
  // Or put this in a method on the returned object
  // if you want to invoke at some point other than load
  $http.get('/some/url').then(function(response) {
    data = response;
  });
  return {
    getData: function() {
      return data;
    }
  };
});

app.controller('SomeController', function($scope, DataBrowser) {
  $scope.data = DataBrowser.getData();
});

However, if the ajax call is complicated enough that you don't want to migrate it at this point, you could simply let the service access it from the global scope rather than make the call itself. 但是,如果ajax调用足够复杂,以至于您此时不想迁移它,则可以简单地让服务从全局范围访问它,而不是自己进行调用。 Or have the current ajax call it throw on $rootScope with something like 或者让当前的ajax调用它在$ rootScope上抛出类似的东西

$('body').scope().dataBrowser = data;

and then inject $rootScope. 然后注入$ rootScope。 I guess the moral of the story is that there are a lot of ways to solve your problem, but in general, it's better not to mix angular with non-angular, not because I think you should care about what angular purists will say (I don't), but because angular is fairly opinionated. 我想这个故事的寓意是有很多方法可以解决你的问题,但总的来说,最好不要将角度与无角度混合,而不是因为我认为你应该关心角度纯粹主义者会说什么(我不要),但因为角度相当自以为是。 Most things just work better when kept within the angular ecosystem. 大多数事物只有在角度生态系统中才能更好地工作。

Yeah so you should store the data in a service or factory typically that also deals with fetching the data and then inject that into a controller for use in the ng-repeat. 是的,所以你应该将数据存储在服务或工厂中,通常也处理获取数据然后将其注入控制器以用于ng-repeat。 I'll put together a basic sample plnkr here. 我将把这里的基本样本plnkr放在一起。

http://plnkr.co/edit/4NYFJ03ldsISSNF3aqoB?p=preview http://plnkr.co/edit/4NYFJ03ldsISSNF3aqoB?p=preview

angular.module('plunker', [])
  .factory('MyDataService', function($http){
    //Using $http here to do the AJAX request

    var service = {};

    service.getData = function(){
      return $http.get('data.json').then(function(resp){
        service.data = resp.data;
      })
    }

    service.getData();

    return service;
  })
  .controller('MainCtrl', function(MyDataService) {
    this.MyDataService = MyDataService;
  });

and the HTML 和HTML

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script data-require="angular.js@1.4.0-rc.0" data-semver="1.4.0-rc.0" src="https://code.angularjs.org/1.4.0-rc.0/angular.js"></script>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl as mainCtrl">
    <p ng-repeat="thing in mainCtrl.MyDataService.data">Hello {{thing.label}}!</p>
  </body>

</html>

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

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