复杂对象上的AngularJS绑定问题

时间:2014-05-02 09:41:56

标签: javascript angularjs

我有从MVC REST服务返回的View Model:

[DataContract]
public class AccountViewModel
{
    [DataMember]
    public IEnumerable<string> Currencies { get; set; }
    [DataMember]
    public IEnumerable<string> FromAccounts { get; set; }
    [DataMember]
    public IEnumerable<string> ToAccounts { get; set; }
}

我有角度的话:

    angular.module('accountServices', ['ngResource'])
        .factory('Accounts', function($resource) {
            return $resource('/SomeUrl/Accounts', {}, {
                get: { method: 'GET' }
            });
        });

    angular.module('staticDataServices', ['accountServices'])
        .service('StaticData', function (Accounts) {

            self.AccountViewModel = Accounts.get();
            self.Reasons = ['Incorrect Alloc',
                            'Unallocated',
                            'Client Withdrawal',
                            'Margin Topup',
                            'Margin Reduction',
                            'Other'];

            return self;
        });

webtraderDeposits.controller('ApprovalDialogController', ['$scope', 'dialog', 'item', 'StaticData', 'Deposits',
    function ($scope, dialog, item, StaticData, Deposits) {
        $scope.AccountViewModel = StaticData.AccountViewModel;
        $scope.Reasons = StaticData.Reasons;
        alert(StaticData.AccountViewModel.Currencies);
    } ]);

StaticData.AccountViewModel是一个对象,但StaticData.AccountViewModel.Currencies未定义。关于我做错了什么想法?

webservice返回以下数据:

<AccountViewModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebtraderBackOffice.RESTService.Models">
<Currencies xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>USD</d2p1:string>
</Currencies>
<FromAccounts xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>59500/FUSD</d2p1:string>
</FromAccounts>
<ToAccounts xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>59504/6227905</d2p1:string>
    <d2p1:string>59504/6227925</d2p1:string>
    <d2p1:string>59504/6227951</d2p1:string>
    <d2p1:string>59504/6227958</d2p1:string>
    <d2p1:string>59504/6227959</d2p1:string>
    <d2p1:string>59505/50203040</d2p1:string>
    <d2p1:string>59505/6567866</d2p1:string>
</ToAccounts>

1 个答案:

答案 0 :(得分:0)

StaticData.AccountViewModel是一个对象,并不意味着它是您期望的对象。由于self.AccountViewModel = Accounts.get();,AccountViewModel几乎可以保证成为一个对象,或者至少某些,无论Accounts.get()返回什么。 Accounts.get()应该返回一个promise对象,其中包含您的Angular应用从服务器获取的内容,以便您需要查看的内容。

如果您的REST服务返回XML,那么这显然是问题所在。 Angular假定使用JSON,因此不会将XML解析为对您有用的任何内容。理想情况下,您应该让Web服务返回JSON而不是XML。怎么做,取决于您的Web服务。对于大多数现代Web框架而言,它相当简单,但我不知道您正在使用哪种类型的Web框架。如果您想要答案,请分享更多相关信息。

如果您没有控制网络服务或者无法让它发送JSON,那么并非全部丢失。有一些方法可以让Angular解析XML。请参阅此问题:How to handle XML services in AngularJS?或此博文:http://rabidgadfly.com/2013/02/angular-and-xml-no-problem/