2015-02-10 17 views
0

我似乎在使用JSON数据填充AngularJS中的select元素时遇到了一些问题。AngularJS基于字符串的JSON键值对

代码:

/* the API returns: {"id":3,"name":"Some Address"} */ 
 

 
app.service("addressService", function($http, $q) { 
 
    var deferred = $q.defer(); 
 
    $http.get('/index.php/Pro/getAddresses').then(function(data) { 
 
    deferred.resolve(data); 
 
    }); 
 
    this.getCounties = function() { 
 
    return deferred.promise; 
 
    }; 
 
}); 
 

 
app.controller('homeController', function($scope, $http, addressService, $routeParams) { 
 
    $scope.availableCounties = {}; 
 

 

 
    var promise = addressService.getCounties(); 
 
    promise.then(function(data) { 
 
    $scope.availableCounties = data; 
 
    }); 
 
});
<select name="sender_address_id" ng-model="sender_address_id" ng-options="county.id as county.name for county in availableCounties"> 
 

 
</select>

当我查看该页面,选择栏仍然无人居住。我也可以控制API。如果使用比json_encode()更好的函数或方法,那也可以解决问题。

编辑,控制台输出鞋子起来就是:

 
Object {data: Object, status: 200, headers: function, config: Object, statusText: "OK"} 
config: Object 
data: Object 
    id: 3 
    name: "Some Address" 

    __proto__: Object 

headers: function (c){a||(a=Xc(b));return c?(c=a[Q(c)],void 0===c&&(c=null),c):a}status: 200 
statusText: "OK" 
__proto__: Object 
+0

如果将其登录到视图中,则为{{availableCounties}}'为空? – DonJuwe 2015-02-10 07:58:50

+0

将数据分配给您的承诺中的availableCounties时,数据的实际外观如何?它可能需要是'in availableCounties'中用于处理ng-options声明的一组对象。 – mindparse 2015-02-10 08:01:26

+0

已更新问题。 :| – on3pk 2015-02-10 08:10:08

回答

0

包装纸的$ HTTP查询到的服务是无用的在这里,因为$ HTTP有一个内置的诺言系统(see documentation),和你不要添加任何逻辑(缓存,数据排序等)。

所以,你可以摆脱你的服务,并使用这个死简单的控制器:

app.controller('homeController', function ($scope, $http) { 
    $scope.availableCounties = []; 

    $http.get('/index.php/Pro/getAddresses') 
     .success(function (data) { 
      $scope.availableCounties = data; 
     }) 
     .error(function (error) { 
      // Eventually do something when request fails 
     }); 
}); 

编辑:

正如评论@kvetis状态,这是一个很好的做法,以保持http请求在一个地方。如果你关心良好的做法,here is a fiddle演示如何简单干净地做到这一点。

+0

我不同意这一点。如果您在更多地方使用相同的API调用,那么使用服务将是一种很好的做法。 – kvetis 2015-02-10 11:34:37

+1

@kvetis是的,我完全同意你:)但是,我们只需要返回服务中的$ http请求,而不是覆盖它的承诺系统。在这里,我不完全确定好的做法是优先事项^^ – Deurco 2015-02-10 11:57:32

+0

是的。确实,您不必使用$ q,只需返回'$ http.get'的结果即可 – kvetis 2015-02-11 10:27:23