没有在App js文件中获取json数组

时间:2015-07-21 04:47:43

标签: javascript json angularjs routes angular-services

我的服务代码如下所示: -

data.service('SmartLearnerService', function ($http) {

//Get Single Records
this.get = function (id) {
    return $http.get("/api/Category/");
    }
});

这是App.js的控制器代码: -

$scope.questionlist = SmartLearnerService.get();

    $scope.questionlist.then(function (pl) {
        var res = pl.data;
        $scope.que = res.QuestionLabel;

    },
                 function (errorPl) {
                     console.log('failure loading Employee', errorPl);
                 });
    console.log($scope.questionlist);

这是web api控制器的控制器代码: -

public class CategoryController : ApiController
{
    CommonDb db = new CommonDb();
    public JsonResult Get()
    {
        var Result = db.GetQuestionById().ToList();

        string message = "No Data Found";

        if (Result.Count() != 0)
        {
            return new System.Web.Mvc.JsonResult()
            {
                Data = Result,
                JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
            };
        }

        else
        {
            return new System.Web.Mvc.JsonResult()
            {
                Data = message,
                JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
            };
        }
    }
   }
}

这里是div标签,我想用ng-repeat指令绑定json结果中的问题。

<div class="question" align="center">{{Questions.QuestionLabel}}</div>

我在控制器的$ scope.questionlist中绑定json数组时遇到问题,我成功从web api控制器获取json结果。

2 个答案:

答案 0 :(得分:0)

好的,如果我不得不猜测(这正是我正在做的事情),你需要在你的控制器中有这样的东西......

SmartLearnerService.get().success(function(questions) {
    $scope.questionList = questions;
});

或者,如果您不喜欢加载项success / error回调

SmartLearnerService.get().then(function(response) {
    $scope.questionList = response.data;
});

并在您的模板中

<div ng-repeat="question in questionList">
    <div class="question" align="center">{{question.QuestionLabel}}</div>
    <!-- and so on -->
</div>

这完全假设您的C#控制器返回类似于......的JSON

 [{
     "QuestionID": "1",
     "QuestionLabel": "Why are mirrors often slightly curved (convex) ?",
     "Image": "zibra-crossing.jpg",
     "Correct": "two",
     "Explaination": "Question one explaination is goes here"
 }, {
 ...
 }]

答案 1 :(得分:-1)

你能试试吗?

SmartLearnerService
            .get()
            .success(function (data, status) {
                if (status === 200) {
                    //your code to process data is here
                }else{alert(status)}
            })
            .error(function (data, status) {
                //TODO: Use nice alert.
                alert('Server request failed with status ' + status + ' while getting area in the ' + $item.Name);
            });

您将获得您正在接收的状态代码,然后您可以相应地更改代码。

我在我的案例中采用的方法是使用NewtonSoft中的JsonConvert进行序列化,然后返回Json对象的字符串而不是Json对象本身以提高速度。