$ scope在$ http.get()

时间:2015-09-18 13:40:59

标签: javascript angularjs

我的角度代码:

angular.module('MyApp',[]).
controller('ProductController', function ($scope, $http) {
    $scope.Product = {};
    $scope.categoryList = null;
    $scope.LoadCategory = function () {

        $scope.a = 'sss';

        $http.get('/Product/GetAllCategory/')
        .success(function (data) {
            if (data.success == true)
            {
                console.log = (data.data);
                $scope.categoryList = data.data;

            }
            else {
                alert('aws');
            }

        })
        .error(function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest + ": " + textStatus + ": " + errorThrown, 'Error!!!');
        })
    };
});

我从这个服务器端代码

使用$ http.get()获取数据
public JsonResult GetAllCategory()
{
    //List<tblCategory> categories = new List<tblCategory>();
    try
    {
        using (CurtainHomesDBEntities dc = new CurtainHomesDBEntities())
        {
            var categories = dc.tblCategory.Select(a => new { a.Id, a.CatagoryName }).ToList();
            return Json(new { data = categories, success = true }, JsonRequestBehavior.AllowGet);
        }

    }
    catch (Exception ex)
    {
        return Json(ex);
    }
}

我使用firebug进行了调试。它从服务器端获取数据并插入$scope.categoryList。但是在if(data.success==true)之外进行调试后,$scope.categoryListundefined

这是什么问题?我找不到。

2 个答案:

答案 0 :(得分:0)

$http.get('/Product/GetAllCategory/')会返回HttpPromise

我会使用以下内容(来自angularjs文档here

// Simple GET request example :
$http.get('/someUrl').
  then(function(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

答案 1 :(得分:-1)

您不需要

if(data.success==true) {...}

因为如果该语句为true,它将运行。使用if(data.success) {...}

$http.get()之外尝试console.log,但请将其包装在:

setTimeout(function () {
    console.log($scope.categoryList)
}, 5000);

我设置5s因为我不知道数据有多大。