无法将JSon绑定到Angular JS中的列表

时间:2014-01-14 10:31:57

标签: javascript json angularjs c#-4.0

我正在开发一个使用角度js的应用程序,我必须使用数据库中的数据填充客户列表,因为我编写了一个Web方法来获取数据

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string  getname()
    {
        SqlHelper sql = new SqlHelper();

        DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");

        Dictionary<string, object> dict = new Dictionary<string, object>();
        object[] arr = new object[dt.Rows.Count];
        List<CustName> custName = new List<CustName>();
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            CustName c = new CustName();
            c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();            
            custName.Add(c);

        }
        dict.Add("JsonCustomer", custName);
        JavaScriptSerializer json = new JavaScriptSerializer();
        return json.Serialize(dict);
        //return "Rhsuhikesh";

    }

}
public class  CustName
 {
    public string cust_F_name { get; set; } 
}

将Json数据捕获为

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

DemoApp.factory('SimpleFactory', function ($http) {
    return {
        getCustomer: function () {
            return $http.post('Home.aspx/getname', { name: "" });
        }
    };
});

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
    SimpleFactory.getCustomer().then(function (customer) {
        $scope.Customer = customer.data;
    }, function (error) {
        // error handling
    });
});

并将其视为

<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
    <title></title>
</head>
<body data-ng-controller="SimpleController">
    <form id="form1" runat="server">
    <div>
        Name<input type="text" data-ng-model="Name" />{{ Name }}
        <ul>
            <li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
        </ul>
    </div>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>

我正在获得o / p

outPut

但我希望它为

Accepted output

json中的数据我必须访问名称值对,但我不明白怎么做,请帮我解决。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

由于您将结果作为JSON字符串获取,因此需要使用 angular.fromJson

将其转换为JavaScript对象

例如:

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
    var customersRawObject = angular.fromJson(customerData);
}, function (error) {
    // error handling
});})

然后你可以做这样的事情:

$scope.customerA=customersRawObject.JsonCustomer[0];