使用AngularJS $ http从API检索和显示数据

时间:2015-04-19 00:20:08

标签: angularjs angularjs-templates

我有这个控制器:

app.controller('BuscadorClientesController', function(){
    this.clientes = [
        {
            tipo: {
                nombre: "Sarasa"
            },
            nombre: "Alan",
            direccion: "Fake Address 1234",
            telefono: "12341234",
            email: "ipsum@gmail.com",
            rubro: "Lorem",
            id: "1"
        }
    ]
});

在我看来,“clientes”数组正在打印正常,但现在我想从我的数据库中获取我的客户端,所以我做了这个

app.service('Clientes', function ($http) {
    this.getAll = function (success, failure) {
        $http.get('/api/clientes')
            .success(success)
            .error(failure);
    }
});

app.controller('BuscadorClientesController', function($scope, Clientes){
    Clientes.getAll(function(data){
        $scope.clientes = data
        console.log($scope.clientes)
    });
});

console.log($ scope.clientes)正在打印正确的数据(包含大量对象的数组),但它没有显示在我的视图中:

<tr ng-repeat="cliente in buscador.clientes">
    <td><%= cliente.tipo.nombre %></td>
    <td><%= cliente.nombre %></td>
    <td><%= cliente.direccion  %></td>
    <td><%= cliente.telefono  %></td>
    <td><%= cliente.email  %></td>
    <td><%= cliente.rubro  %></td>
</tr>

我做错了什么?

编辑:

我将控制器代码更改为:

app.controller('BuscadorClientesController', function(Clientes){
    var that = this
    Clientes.getAll(function(data){
        that.clientes = data
        console.log($scope.clientes)
    });
});

这是正确的方法还是有更好的方法?

2 个答案:

答案 0 :(得分:2)

如果您使用controller as语法,那么您编辑的代码是正确的。

<强>控制器:

app.controller('BuscadorClientesController', function(Clientes){
    var vm = this;
    Clientes.getAll(function(data){
        vm.clientes = data;
        console.log(vm.clientes);
    });
});

<强> HTML:

<tr ng-repeat="cliente in buscador.clientes">
    <td><%= cliente.tipo.nombre %></td>
    <td><%= cliente.nombre %></td>
    <td><%= cliente.direccion  %></td>
    <td><%= cliente.telefono  %></td>
    <td><%= cliente.email  %></td>
    <td><%= cliente.rubro  %></td>
</tr>

如果不是,则clientes位于您的范围内,不应以buscador作为前缀:

<强>控制器:

app.controller('BuscadorClientesController', function($scope, Clientes){
    Clientes.getAll(function(data){
        $scope.clientes = data
        console.log($scope.clientes)
    });
});

<强> HTML:

<tr ng-repeat="cliente in clientes">
    <td><%= cliente.tipo.nombre %></td>
    <td><%= cliente.nombre %></td>
    <td><%= cliente.direccion  %></td>
    <td><%= cliente.telefono  %></td>
    <td><%= cliente.email  %></td>
    <td><%= cliente.rubro  %></td>
</tr>

答案 1 :(得分:0)

您使用的方法不正确,无法显示变量。在AngularJS中,您必须使用ngBindexpressions

您的观点应如下所示:

<tr ng-repeat="cliente in buscador.clientes">
  <td ng-bind="cliente.tipo.nombre"></td>
  <td ng-bind="cliente.nombre"></td>
  <td ng-bind="cliente.direccion"></td>
  <td ng-bind="cliente.telefono"></td>
  <td ng-bind="cliente.email"></td>
  <td ng-bind="cliente.rubro"></td>
</tr>