我对Angularjs ng-repeat做错了什么?

时间:2013-04-29 15:02:50

标签: javascript asp.net-mvc json angularjs angularjs-directive

我现在已经尝试了几个小时应该这么容易,但我不明白为什么我不能让这个工作。

虚拟列表仅用于测试它应该工作,它确实有效。但是,当我连接我的服务器端数据源时。 ajax调用返回的Json与虚拟列表中的Json相同。

我做错了什么?

以下是dummylist的工作示例链接:http://plnkr.co/edit/6nBkdBpPVqQ2P8u2BEeY

服务器端是.NET MVC 4应用程序。

HTML:

 <div data-ng-controller="currencyController">
     <ul>

       <li data-ng-repeat="currency in currencies"><span>{{ currency.CurrencyCode}} - </span><span>{{ currency.CurrencyName }}</span>
   </li>

     </ul>
 </div>

JS:

var currencyTools = angular.module('currencyTools', []);

currencyTools.controller('currencyController',function(currencyService,$scope) {
   var path = 'currency/GetCurrencies';
   currencyService.getAllCurrencies(path, function (jsonResult) {
        $scope.currencies = jsonResult.data;
    });
   // $scope.currencies = dummyList(); //if i uncomment this it works
})





currencyTools.factory('currencyService', function () {
    var service = {
        getAllCurrencies: function (path, callback) {
            var result = $.ajax({
                url: path,
                type: 'GET',
                dataType: 'json',
                data: '',
                contentType: 'application/json; charset=utf-8',
                success: function(json) { callback(json); }
            });
            return result;
        }
    };
    return service;
});


function dummyList() {
    return [
    {  "CurrencyCode": "BAM", "CurrencyName": "Bosnia-Herzegovina Convertible Mark" },
    {  "CurrencyCode": "BBD", "CurrencyName": "Barbadian Dollar" }, 
    {  "CurrencyCode": "BDT", "CurrencyName": "Bangladeshi Taka" },
    { "CurrencyCode": "BGN", "CurrencyName": "Bulgarian Lev" },
    {  "CurrencyCode": "BHD", "CurrencyName": "Bahraini Dinar" },
    {  "CurrencyCode": "BIF", "CurrencyName": "Burundian Franc" }, 
    {  "CurrencyCode": "BMD", "CurrencyName": "Bermudan Dollar" }, 
    {  "CurrencyCode": "BND", "CurrencyName": "Brunei Dollar" }, 
    {  "CurrencyCode": "BOB", "CurrencyName": "Bolivian Boliviano" },
    {  "CurrencyCode": "BRL", "CurrencyName": "Brazilian Real" }, 
    {  "CurrencyCode": "BSD", "CurrencyName": "Bahamian Dollar" }, 
    {  "CurrencyCode": "BTC", "CurrencyName": "Bitcoin" }];
}

1 个答案:

答案 0 :(得分:3)

这里有一些问题。

  1. $.ajax是一个异步调用,它返回一个promise,而不是一个值。所以你的getAllCurrencies方法正在返回一个承诺。您真正需要做的是订阅该promise的success()函数并等待值从服务器返回。 ......但是......
  2. 不要使用JQuery在Angular应用程序中执行AJAX。你应该几乎不需要这样做。请改用$http。它将确保在返回ajax后触发摘要。
  3. 如果必须使用JQuery的AJAX,则在更新范围后必须使用$apply
  4. Here's an updated plunker with an example of doing it in a more "angular" way.